Memory map for a 2D array in C
Solution 1:
See my question here.
That is not the way you access information about 2-d arrays. In fact, you can just think of them as 1-d, where you multiply and add the indices in a special way.
e.g.
int x[10] = {0,1,2,3,4,5,6,7,8,9};
int y[2][5] = {{0,1,2,3,4},{5,6,7,8,9}};
These are formatted exactly the same in memory, and they look like this:
|0|1|2|3|4|5|6|7|8|9|
So to get the 8
element, you can either ask for x[8]
, or y[1][3]
.
For the second way, you can think of it as (1 * 5) + 3
.
This is why your first 4 were the same. You have:
-
arr
: this is the address of the start of the array -
arr[0]
: this is address of the start of the first sub-array, which is the same as the start of the overall array -
&arr[0][0]
: this is the address of first element of the first sub-array, also the start of the overall array -
arr[0][0]
: this is the value stored in the first element of the first sub-array.
Solution 2:
Your code just uses a plain multidimensional array, but the image describes an array of pointers, like the kind you usually make when malloc-ing things.
A multidimensional array is basically just a normal, flattened, array (in memory) with some extra syntatic sugar for accessing. So while it is possible to get a pointer from arr[i], there isn't an extra "variable" just to store this, as happens in your image.
To correct the image, remove the parts with the arr[0], arr[1]...
and change the value of arr
to 1245039
(the same as &arr[0][0]).