Reputation: 1305
I always thought that x[i] is equivalent to *(x+i)
.
So that would x[i][j] is equivalent to *(*(x+i)+j)
, which is in this case implies that a 2D array must be implemented as an array of pointers, each of these pointers has to be dereferenced.
But I learned that you can create a 2D array on the heap this way :
char (*arr)[256]=malloc(512*256);
If the former hypothesis is right, then arr[i][j] would access an unauthorized location (since we are dereferencing two times).
Is my former hypothesis wrong in case of 2d arrays ?
Upvotes: 0
Views: 107
Reputation: 213862
x[i]
is indeed equivalent to *(x+i)
. Pointer arithmetic is used in the latter form.type array[x][y];
, then you have to apply the above rule in several steps. array
when used in an expression, decays to a pointer to the first element, in this case of type type(*)[y]
- an array pointer pointing at the first array in the array of arrays. Do not confuse an array pointer with "an array of pointers", which means something different entirely.array + i
performs pointer arithmetic on such an array pointer. *(array + i)
gives the pointed-at item, a 1D array.If you for some reason unknown want to access an individual item in the 2D array by using pointer arithmetic only, you would therefore have to write something obscure like this:
*( *(array + i) + j)
If the former hypothesis is right, then arr[i][j] would access an unauthorized location (since we are dereferencing two times).
Well, it wasn't right. When you have an array pointer such as char (*arr)[256]
, then you can access the items as arr[i][j]
. Note that arr[i]
performs the same kind of pointer arithmetic, so you get "the char[256] array number i
". And in that array you then access item j
.
This is actually the reason why this syntax is used. Had you written the malloc more type correct like this:
char (*arr)[512][256]=malloc( sizeof(char[512][256]) );
then you would have to de-reference the array pointer before using it, (*arr)[i][j]
or otherwise you would get pointer arithmetic on whole 2D arrays.
The question Correctly allocating multi-dimensional arrays explains and illustrates the differences between look-up tables based on arrays of pointers and true multi-dimensional arrays.
Upvotes: 1