Please consider the following 2-D Array:
int array[2][2] = {
{1,2},
{3,4}
};
As per my understanding:
– ‘array’ represents the base address of the 2-D array (which is the same as address of the first element of the array, i.e array[0][0]).
-
The actual arrangement of a 2-D Array in memory is like a large 1-D Array only.
-
Now, I know that base address = array. Hence, I should be able to reach the Memory Block containing the element: array[0][0].
-
If I forget about the 2-D array thing & try to treat this array as a simple 1-D array:
array[0] = *(array+0) gives the base address of the first array & NOT the element array[0][0]. Why? -
A 2-D array does not store any memory address (like an Array of Pointers).
-
If I know the base address, I must be able to access this memory as a linear 1- Dimensional Array.
Please help me clarify this doubt.
Thanks.
Arrays are not pointers.
In most circumstances1, an expression of type “N-element array of
T” will be converted (“decay”) to an expression of type “pointer toT“, and the value of the expression will be the address of the first element of the array.The type of the expression
arrayis “2-element array of 2-element array ofint“. Per the rule above, this will decay to “pointer to 2-element array ofint(int (*)[2]) in most circumstances. This means that the type of the expression*array(and by extension,*(array + 0)andarray[0]) is “2-element array ofint“, which in turn will decay to typeint *.Thus,
*(array + i)gives you thei‘th 2-element array ofintfollowingarray(i.e., the first 2-element array of int is atarray[0](*(array + 0)), and the second 2-element array ofintis atarray[1](*(array + 1)).If you want to treat
arrayas a 1-dimensional array ofint, you’ll have to do some casting gymnastics along the lines ofor
1. The exceptions are when the array expression is an operand of the
sizeofor unary&operators, or is a string literal being used to initialize another array in a declaration.