0

multi-dimensional array vs pointers

int a[3][2] = {{3,6}, {8,4}, {7,1}}; cout << *a[1] << *(*a+1); // outputs 86 Three rows and two columns. Does a[1] imply a[1][0]? How does *(*a+1) give a[0][1] ? I do not know how pointers are used in this case.

23rd Jul 2020, 12:08 PM
Solus
Solus - avatar
1 ответ
+ 1
Multidimensional arrays are stored linear just as normal arrays. So your 2D array looks like this in memory: int a[6] = {3, 6, 8, 4, 7, 1}; The compiler however knows how to handle the array. a[1] returns the address to the second block of the outer array, so it points to the 8. *(*a+1) however increments the starting address of the array by one so it points to 6. It might seem a bit weird and it is in some way so I recommend to always use the full address of the element you want to select. So I'd write &a[1][0] instead of a[1] because it more clear.
23rd Jul 2020, 12:24 PM
Aaron Eberhardt
Aaron Eberhardt - avatar