C Programming in One Hour a Day has this quote:
As with a one-dimensional array, the name of a multidimensional array is a pointer to the first array element.
#include <stdio.h>
int m[2][4];
int main() {
printf("%p\n", m); // 1
printf("%p\n", &(m[0])); // 2
printf("%p\n", m[0]); // 3
printf("%p\n", &m[0][0]); // 4
}
This prints the same value for all the statements. Based on the quote, it makes sense that 1 == 2 and 3 == 4. But I don't understand how 2 == 3. How could the address of m[0] be the same as m[0]?
When a two dimensional (or any dimensional) array is allocated, it just occupies the memory for its elements (memory is not allocated to the array name or any other array elements like m[0] and m[1] in your case, which acts like const pointers).
Because there will not be any physical memory allocated to those (actually not even needed), you'll get the same address when tried to print those. In your case,
as it is a 2 dimensional array, as m points to m[0] which in turn points to m[0][0], fetching address of all these will give the same values ( also for m[1] and m[1][0]).
**For better understanding, see this (this is how it will be if you print those)
_____ _____ _____
|0x100| --> |0x100| --> |value|
0x100|_____| 0x100|_____| 0x100|_____|
m m[0] m[0][0]
*value is the value of m[0][0]
Here,
m and m[0] acts like pointers but are not physically implemented (doesn't occupy memory) and the compiler handles how to treat those.
*Though I have shown that 0x100 contains 0x100 for m and m[0], 0x100 actually contains the data/value of m[0][0], but if you do any operations that is how the compiler treats them.
**And because of that, int *p = malloc(n * sizeof(int)) this is possible with the difference that p now occupies memory which points to starting address of array. If you consider p as int const *p, you can treat it like a normal array without dynamic allocation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With