14

I've known that this is true:

x[4] == 4[x]

What is the equivalent for multi-dimensional arrays? Is the following true?

x[4][3] == 3[x[4]] == 3[4[x]]
Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
ypercubeᵀᴹ
  • 113,259
  • 19
  • 174
  • 235

2 Answers2

15

x[y] is defined as *(x + (y))

x[y][z] would become *(*(x + (y)) + z)

x[y[z]] would become *(x + (*(y + (z))))


x[4][3] would become *(*(x + (4)) + 3) would become *(*(x + 4) + 3)

3[x[4]] would become *(3 + (*(x + (4)))) would become *(*(x + 4) + 3)

3[4[x]] would become *(3 + (*(4 + (x)))) would become *(*(x + 4) + 3)

Which means they are all equivalent.

Pubby
  • 51,882
  • 13
  • 139
  • 180
  • In the case of a multidimensional array `int x[5][7]` you'd have `x[y][z]` defined as `*(x + 7*y + z)`. And `x[y]` would become `x + 7*y` i.e. the pointer to the indicated slice. But I believe the equivalences still hold, even if the expanded expressions are somewhat longer. If the compiler does accept the code at all, that is. – MvG Jul 31 '12 at 23:16
1

Yes. In each case x is an array which decays to a pointer and then has pointer arithmetic performed on it.

Mankarse
  • 39,818
  • 11
  • 97
  • 141