6
Contributors
8
Replies
9
Views
6 Years
Discussion Span
Last Post by Narue
0

int a[10];
a[-1]=3;
cout<<a[-1];

When I execute this code, it gives runtime error!!!!!!!!!
"Stack around the variable 'a' was corrupted"

0

>>Give names of some languages that use negative array index

A couple centuries ago I worked with a version of HP BASIC that would let you use negative index values without doing any of the tricks as previously posted in this thread. When the array is declared you specified both the upper and lower range of index values, for example if you wanted an array with index values between -10 and +10 you would declare it as DIM MyArray[-10,10] as Int or something like that.

0

@Caligulaminus
int a[10];
int* b = a;
b++;
b[-1] = 123;

I don't understand why you have done b++

0
int a[10];
int* b = a;//b pointing to a[0]
b++;//now b pointing to a[1]
//b[0] == a[1] 
//b[-1] == a[0]
b[-1] = 123;//exact same thing as 'a[0] = 123;'

Edited by dospy: n/a

0

I don't understand why you have done b++

Negative indices are syntactically allowed, but the index also has to be valid. Arrays in C are 0-based, which means if you want to index them with negative values, you need to shift the "beginning" of the array forward enough to make the negative index valid:

int a[] = {0,1,2,3,4,5};
int *b = a;

/*
a: [0][1][2][3][4][5]
    ^
    |
    b
*/

++b;

/*
a: [0][1][2][3][4][5]
       ^
       |
       b
*/

b[-1] = 123;

/*
a: [123][1][2][3][4][5]
         ^
         |
         b
*/
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.