对于 Pointer & 的 strlen 和 sizeof 的不同答案基于数组的字符串初始化
可能的重复:
C:指针和数组之间的差异
结果大小不同
做了......
char *str1 = "Sanjeev";
char str2[] = "Sanjeev";
printf("%d %d\n",strlen(str1),sizeof(str1));
printf("%d %d\n",strlen(str2),sizeof(str2));
而我的输出是
7 4
7 8
我无法给出sizeof str1
为 4 的原因。请解释它们之间的区别。
Possible Duplicates:
C: differences between pointer and array
Different sizeof results
Basically, I did this...
char *str1 = "Sanjeev";
char str2[] = "Sanjeev";
printf("%d %d\n",strlen(str1),sizeof(str1));
printf("%d %d\n",strlen(str2),sizeof(str2));
and my output was
7 4
7 8
I'm not able to give reasons as to why the sizeof str1
is 4. Please explain the difference between these.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为 sizeof 给出了数据类型的大小(以字节为单位)。 str1的数据类型是char*,占4个字节。相反, strlen 为您提供chars 中字符串的长度,不包括空终止符,因此为 7。 sizeof str2 是 8 字节的 char 数组,它是包括空终止符的字符数。
请参阅 C-FAQ 中的此条目:http://c-faq.com /~scs/cclass/krnotes/sx9d.html
试试这个:
Because sizeof gives you the size in bytes of the data type. The data type of str1 is char* which 4 bytes. In contrast, strlen gives you the length of the string in chars not including the null terminator, thus 7. The sizeof str2 is char array of 8 bytes, which is the number of chars including the null terminator.
See this entry from the C-FAQ: http://c-faq.com/~scs/cclass/krnotes/sx9d.html
Try this:
str1
是一个指向 char 的指针,系统上指针变量的大小为 4。str2
是一个栈上的char数组,存放8个字符,"s","a","n","j","e","e","v"," \0" 因此其大小为 8重要的是要注意,指向各种数据类型的指针的大小将相同,因为它们指向不同的数据类型,但它们仅占用该系统上的指针大小。
str1
is a pointer to char and size of a pointer variable on your system is 4.str2
is a array of char on stack, which stores 8 characters, "s","a","n","j","e","e","v","\0" so its size is 8Important to note that size of pointer to various data type will be same, because they are pointing to different data types but they occupy only size of pointer on that system.
sizeof(str1) 是 sizeof(char*)
而
sizeof str2 是 sizeof(char array)
sizeof(char array) 应等于 strlen(char array) + 1(NULL 终止)。
如果将 char 数组传递给函数,则 sizeof 显示的其大小将会改变。原因是 char 数组仅作为 char* 传递。
sizeof(str1) is sizeof(char*)
whereas
sizeof str2 is sizeof(char array)
sizeof(char array) should be equal to strlen(char array) + 1 (NULL termination).
Well if you pass the char array to a function, its size as shown by sizeof will change. The reason is char array is passed as char* only.
strlen()
给出字符串的长度,即7
。sizeof()
是一个编译时运算符,sizeof(str1)
给出了实现上指针的大小(即4
)。sizeof(str2)
给出数组的大小,即8*sizeof(char)
即8
[包括NUL
代码>终止符]strlen()
gives the length of the string which is7
.sizeof()
is a compile time operator andsizeof(str1)
gives the size of pointer on your implementation (i.e4
).sizeof(str2)
gives the size of the array which is8*sizeof(char)
i.e.8
[including theNUL
terminator]