据我了解,指针“名称”本身占用 8 个字节。如何
内存中占用4个字节的第一个字符串“xxx”可以在
与指针位置相同?
那是因为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
总而言之,数组和指针是不同的类型。指针存储地址,数组存储它们定义要存储的类型的值。在某些情况下,数组计算为其第一个元素的地址。这就是数组和指针之间的相似性结束的地方。