0
#include <stdio.h>

int main()
{   
    int array[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    printf("%d\n", array[1][-2]); // 2
    printf("%d\n", (-1)[array][5]);  // 3
    printf("%d\n", -1[array][5]);  // -9

    return 0;  
}

What is the meaning of [array]? why output 3? -9? thank you!

Fred Hu
  • 161
  • 1
  • 7
  • 1) arrays are stored in contiguous memory 2) read about pointer arithmetic. – Sourav Ghosh Feb 19 '19 at 07:23
  • While the duplicate answers the issue about the weird notation where `array[index]` is also equal to `index[array]`, your code does contain a few other things that makes it bad and technically *undefined behavior* as you go out of bounds of your arrays. Where did you find this example? Please don't use that source again. – Some programmer dude Feb 19 '19 at 07:24
  • @Someprogrammerdude Where does the code go outside the bounds? All three examples result in an address inside the bounds of the given array. `[1][-2]` is equivalent to `[0][3-2]`, `[-1][5]` is equivalent to `[0][5-3]` and `[1][5]` is `[2][5-3]`. – glglgl Feb 19 '19 at 07:29
  • 1
    @glglgl `array` is an array of three arrays of three `int`. That means `array[1]` is an array of three `int`. The index `-2` is out of bound of that array. Yes it's "in bounds" of the memory for the whole of `array`, but for `array[1]` is it out of bounds. The same for index `5` or `-1`. The code as shown is simply bad and doesn't show anything useful IMO. – Some programmer dude Feb 19 '19 at 07:30
  • 1
    Array values will be calculated from head address that is array, since it is a pointer, not `array[i][j] = *(array + (i*(n)+j)sizeof(type))` . So in case 1 array + 1*3 - 2 i.e. array + 1, values at this address is 2. But this is a really bad practice to use negative indices – Anil Feb 19 '19 at 07:36
  • Also very important here is the issue of [*operator precedence*](https://en.cppreference.com/w/c/language/operator_precedence). – Some programmer dude Feb 19 '19 at 07:36
  • I know that for a two-dimensional array int arr[M][N], the address of arr[i][j] is (*arr) + i * N + j, and its value is * ((*arr) + i * N + j), I didn't know a[5] == 5[a] before, thank you all. – Fred Hu Feb 19 '19 at 07:50
  • @Someprogrammerdude Oh, I didn't know that this is important as well. I always thought that would be ok because the three arrays are by definition adjacent to each other. But even if it was valid, it would be bad style, granted. – glglgl Feb 19 '19 at 09:40

1 Answers1

1

In C, given two expressions E1 and E2, the syntax:

E1[E2]

is exactly equivalent to:

E2[E1]
Acorn
  • 24,970
  • 5
  • 40
  • 69