0

I have two arrays and out of both I have to get the Values of specific Indices. While doing this I have comme accross something odd. When I print out the value at index -1 of arr1, I get 0 and the same thing happens with index 8. I concluded that inidces outside the range of an array are returned as 0. Now my problem. When I do the same thing with arr2, I get 29 as the Value of index -1.
What am I doing wrong?

int arr1[] = {33, 12, 75, 85, 62, 14, 100, 29};

printf("Nummer -1: %d\n",arr1[-1]); //outputs 0
printf("Nummer 8: %d\n",arr1[8]; //outputs 0


int arr2[] = {85, 15, 84, 96, 4, 45, 55, 12, 25, 68};
printf("Nummer -1: %d\n",arr2[-1]); //outputs 29

Note: I use Code:Blocks on Linux Mint with the gcc compiler

2 Answers2

4

I concluded that indices outside the range of an array are returned as 0.

That's a wrong conclusion to draw: accessing indices outside the range of an array produces undefined behavior. The access may also produce arbitrary values, but it could also crash your program: once undefined behavior is invoked, the program is in an invalid state.

When I do the same thing with arr2, I get 29 as the Value of index -1.

In this particular case your program appears to read a value from a different array (i.e. the last value in arr1). This is still undefined behavior, though, so doing this results in an invalid program.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Negative array index illegal in C and C++. it is invoked undefined behaviour in C.

From C11 §6.5.2.1 Array subscripting

A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

Clang compiler generated warning

warning: array index -1 is before the beginning of the array [-Warray-bounds]
printf("Nummer -1: %d\n",arr1[-1]); //outputs 0
msc
  • 33,420
  • 29
  • 119
  • 214