Give names of some languages that use negative array index?

Recommended Answers

C and C++.

a[-1] is valid syntax.

Jump to Post
int a[10];
int* b = a;
b++;
b[-1] = 123;
Jump to Post

All 8 Replies

C and C++.

a[-1] is valid syntax.

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"

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

>>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.

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

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

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;'

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

if he didn't the program would crash because there is no such value as a[-1]

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
*/
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.