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

Someone told me as an answer to my last question , which

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

changed by 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 a result, it gives me:

0xfff0000f0
0xfff0000f0
xxx
x

Can you explain to me how the address of the name pointer matches the address that the name pointer points to? In my opinion, the pointer "name" itself takes 8 bytes. How does the first line “xxx”, which occupies 4 bytes in memory, be in the same place as the pointer?

+4
source share
5 answers

, , name C, - . , . . .

-, , . A

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

, - .

+7

"xxx", printf("%p\n", name[0]); . , name and address of "xxx" wont be the same. name array of pointer, "xxx 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"
+4

name array of char* pointer to char*, - . &name pointer to char* [2], - , .

, C. "", C. C . , ( , ).

:

char (*p)[2] = &name;
printf("%p", &p);

address of a pointer to an array, , , name &name.

+2

, "" , ""?

&name ( XXX YYY) name , .. XXX ( ). (), &name name, &name name .

+2

"" 8 . "xxx", 4 , , ?

, name - , . - , , - , . , . , C - .

- , ( ) . :

void f(char p[]); // p is a pointer, not an array

// This is exactly the same as

void f(char *p); 

char s[] = {'h', 'e', 'l', 'l', 'o'};
f(s);   // here s decays to a pointer to its first element

// another example

char t = "hello"[1]; // the string literal decays to a pointer to its first element

, ( ):

char s[] = "hello";
char *t = "hello"; // string literal decays into a pointer

printf("%d", sizeof s);  // prints 5
printf("%d", sizeof t);  // prints 4 or 8 depending on the pointer size on the machine
printf("%d", sizeof *t);  // prints 1

// taking your example

char *name[] = {"xxxx", "yyyy"}; // yet another case where string literals decay to a pointer

printf("%p", name); // name is an array but here decays to a pointer
printf("%p", &name); // &name is a pointer to an array of 2 pointers to characters

name, &name printf, . , :

printf("%p", name + 1);
printf("%p", &name + 1);

printf("%d", *(&name + 1) - name); // prints the length of the array

To summarize, arrays and pointers are of different types. Pointers store addresses, arrays store values ​​of the type that they are defined for storage. In some situations, arrays evaluate at the address of their first element. That similarity ends between arrays and pointers.

+2
source

Source: https://habr.com/ru/post/1526005/


All Articles