I've just finished the С language course at the university. I was told how variables are stored in the pc memory and that arays are stored successively. That's seen in following example:
#include <stdio.h>
void main(){
char a[3][6];
printf("[0][0]->%p \t[1][0]->%p\t [0][5] %p \n", &a[0][0],&a[1][0], &a[0][5]);
printf("%p %p", a, &a[0][0]);
}
The output will be like:
[0][0]->0061FF06 [1][0]->0061FF0C [0][5] 0061FF0B
0061FF06 0061FF06
AND! The adress of a
will be the same as the adress of a[0][0]
.
And the sizeof(a) is 18(in this example).
But... when it comes to dynamic arrays... Here, see for yourself.
#include <stdio.h>
#include <stdlib.h>
void main()
{
char **a = (char **)malloc(3 * sizeof(char*));
for(int i=0; i < 3; i++)
a[i] = (char *)malloc(6 * sizeof(char));
printf("[0][0]:%p [1][0]%p [0][5]%p\n", &a[0][0], &a[1][0], &a[0][5]);
printf("a:%p [0][0]: %p\n", a, &a[0][0]);
printf("[1][0] - [0][5] = %d \n", &a[1][0] - &a[0][5]);
printf("%d", sizeof(a) );
}
The resukt will be like:
[0][0]:00AD1588 [1][0]00AD1598 [0][5]00AD158D
a: 00AD15D8 [0][0]: 00AD1588
[1][0] - [0][5] = 11
4
- WHY in dynamic
[1][0] - [0][5]
isn't equal to 1 (as in static arrays) ? - WHY in dynamic
sizeof(a)
is 4 ? - WHY in dynamic adresses of
a
and&a[0][0]
don't concide ?