I know that for single-dimensional arrays x=a[i] is equivalent to x=*(a+i), but how can I access elements of a two-dimensional arrays using pointers?
I know that for single-dimensional arrays x=a[i] is equivalent to x=*(a+i) , but how
Share
Summary: If you have a multidimensional array defined as
int [][], thenx = y[a][b]is equivalent tox = *((int *)y + a * NUMBER_OF_COLUMNS + b);Boring Details:
The
(int *)cast ofyabove deserves some explanation, as its necessity may not be at-first intuitive. To understand why it must be there consider the following:Typed pointer arithmetic in C/C++ always adjusts the typed pointer value (which is an address) by the size of the type in bytes when adding/subtracting/incrementing/decrementing by scalar.
The fundamental type of a multi-dimensional array declaration (not the element type; the variable type) is an array-type of one-less dimension than the final dimension.
The latter (#2) of these really needs an example to solidify. In the following, variables
ar1andar2are equivalent declarations.Now the pointer arithmetic part. Just as a typed structure pointer can be advanced by the size of the structure in bytes, so can a full dimension of an array be hopped over. This is easier to understand if you think of the multi-dimensioned array as I declared ar2 above:
All of this goes away with a bare pointer:
Therefore, when doing the pointer arithmetic for two-dimensional array, the following would NOT work in getting the element at
[2][2]of a multi-dimensioned array:The reason is hopefully obvious when you remember that
yis an array of arrays (declaratively speaking). The pointer arithmetic of adding the scaler(2*5 + 2)toywill add 12 rows, thereby computing and address equivalent to&(y[12]), which is clearly not right, and in fact, will either throw a fat warning at compile time or outright fail to compile altogether. This is avoided with the cast of(int*)yand the resulting type of the expression being based on an bare pointer-to-int: