Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creates two pointers? char *name[] = {"xxx", "yyy"}

Somebody told me as an answer to my last question that

char *name[] = {"xxx", "yyy"}

is changed by the compiler to

char *name[] = {Some_Pointer, Some_Other_Pointer};

I tried the following for understanding:

printf("%p\n", &name);
printf("%p\n", name);
printf("%s\n", *name);
printf("%c\n", **name);

So as an output it gives me:

0xfff0000f0
0xfff0000f0
xxx
x

Can you explain to me how the address of the pointer "name" is the same as the address where the pointer "name" is pointing to? From my understanding the pointer "name" itself occupies 8 bytes. How can the first string "xxx" which occupies 4 bytes in memory be at the same location as the pointer?

like image 695
Jan Avatar asked Dec 03 '22 20:12

Jan


2 Answers

First of all, when you have any array like name in C, the value of the array is the address of its first element. Note that this value is not stored in some variable. It is used as an immediate value in the compiled assembly code. So it doesn't makes sense to think about its address.

Second, since an array is stored in memory as a bunch of consecutive location, the address of the array is defined the address of the first element. So for any array A you have the following equality of addresses

 &(A[0]) == A == &A

It doesn't change anything to that if you have array of pointer or whatever.

like image 121
hivert Avatar answered Dec 05 '22 10:12

hivert


To view the address of "xxx" you should print printf("%p\n", name[0]); like this. Surely address of name and address of "xxx" wont be the same. Here name is array of pointer which holds the address of "xxx and yyy".

printf("%p\n", &name);
printf("%p\n", name);
printf("%p\n", name[0]); address of "xxx"
printf("%p\n", name[1]); address of "yyy"
like image 37
mahendiran.b Avatar answered Dec 05 '22 10:12

mahendiran.b