In the following example code, I use string as array, if the name of str is an pointer to the first element of the str, in this case the first character of string, which is s, the size of str, should be 8, but it gives the 6 instead.
#include <stdio.h>
char str[] = "string";
char *ptr = "string";
int main(void){
int first = sizeof(str);
int second = sizeof(str[0]);
int third = sizeof(ptr);
int size_of_array = sizeof(str)/sizeof(str[0]);
printf("the size is %d, %d, %d, %d", size_of_array, first, second, third);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
看起来str不是指针,str的大小不是ptr的大小?我很困惑
长话短说; 数组不是指针,指针不是数组.
由于隐式转换,您似乎能够在需要指针的上下文中使用数组1 许多新手(并且经历了可悲的经历),开发人员会混淆两者.
你自己的代码片段是一个完美的例子,因为数组不是指针,而指针不是数组.
1. "重要的是要注意,在许多情况下,数组会衰减为指针,因为这是混淆的持续来源." - Ed S.
你sizeof的操作将使用变量的"真实"类型,这就是为什么你得到的数字与数组名称等同于指针的假设不符.
只是为了让读者清楚这个问题; 数组不是指针,指针不是数组..
首先,问题的关键:编译器严格按照声明大小处理sizeof .在以下代码中,假设指针变量保存32位(4字节)地址:
char str1[] = "abcd";
char *pstr = str1;
// str1 is declared to be a fixed array of 5 chars (4+nul)
size_t str1size = sizeof(str1); // str1size = 5;
// pstr is declared to be a 32 bit pointer to a memory address.
size_t pstrSize = sizeof(pstr) // size of a 32 bit pointer; 4.
Run Code Online (Sandbox Code Playgroud)
要掌握你所看到的结果,请回顾一下数组和指针变量的差异(其中大多数人认为比较少).
数组和指针变量之间C的核心差异是
第一个我根本不能强调,如果你想真正包围C中的数组和指针.除此之外,他们的关系充其量只是乱伦.指针变量位于数组(或任何其他变量)之类的地址.但与数组不同,它们也有一个地址作为它们的价值.数组是他们的地址.
第一个最好的证明如下:
char str1[] = "abcd";
char *pstr = NULL;
pstr = str1; // ok. pstr holds the address *at* str1.
str1[0] = *pstr; // ok. copies 'a' on to 'a'.
pstr++; // ok. increment the address held in pstr by one item (char) size.
str1[0] = *pstr; // ok. copies 'b' over 'a'.
pstr = str1+1; // ok. pstr holds the address *at* str1 + one item (char) size.
str1 = pstr; // does not compile. str1's address cannot be changed.
Run Code Online (Sandbox Code Playgroud)
请注意,指针变量本身包含一个地址,而固定数组是一个地址.因此最后的陈述完全正确.
pstr = str1; // ok. put the str1 address in pstr, a pointer variable.
Run Code Online (Sandbox Code Playgroud)