用细绳的sizeof行为 [英] Behaviour of sizeof with string
问题描述
#include <stdio.h>
#include <string.h>
int main()
{
printf("%d\n",sizeof("S\065AB"));
printf("%d\n",sizeof("S65AB"));
printf("%d\n",sizeof("S\065\0AB"));
printf("%d\n",sizeof("S\06\05\0AB"));
printf("%d\n",sizeof("S6\05AB"));
printf("%d\n",sizeof("\0S65AB"));
return 0;
}
输出:
5
6
6
7
6
7
任何人都可以用字符串解释这种现象?
Can anyone explain this behaviour with character strings?
在Debian 7.4使用GCC
Using GCC on Debian 7.4
推荐答案
字符串文字的大小内的字符包括添加了结尾的空字节数。如果存在嵌入字符串中的空值,它们是不重要的;他们得到计数。这是无关的的strlen()
只是如果文字不包含嵌入的空值,的strlen(S)==的sizeof(S) - 1
。
The size of a string literal is the number of characters in it including the trailing null byte that is added. If there embedded nulls in the string, they are immaterial; they get counted. It is unrelated to strlen()
except that if the literal includes no embedded nulls, strlen(s) == sizeof(s) - 1
.
printf("%zu\n", sizeof("S\065AB")); // 5: '\065' is a single character
printf("%zu\n", sizeof("S65AB")); // 6
printf("%zu\n", sizeof("S\065\0AB")); // 6: '\065' is a single character
printf("%zu\n", sizeof("S\06\05\0AB")); // 7: '\06' and '\05' are single chars
printf("%zu\n", sizeof("S6\05AB")); // 6: '\05' is a single character
printf("%zu\n", sizeof("\0S65AB")); // 7
注意'\\ 377'
是一个有效的八进制常量,相当于'\\ XFF
或255。您可以在字符串中使用它们了。值'\\ 0'
是仅一个更一般的八进制常数的一个特例。
Note that '\377'
is a valid octal constant, equivalent to '\xFF'
or 255. You can use them in strings, too. The value '\0'
is only a special case of a more general octal constant.
注意的sizeof()
计算为类型的值为size_t
,并在C99正确的格式类型修饰符和C11为为size_t
是以Z
,并且因为它是无符号, U
比更合适 D
,所以我使用了%祖\\ N
格式。
Note that sizeof()
evaluates to a value of type size_t
, and the correct formatting type qualifier in C99 and C11 for size_t
is z
, and since it is unsigned, u
is more appropriate than d
, hence the "%zu\n"
format that I used.
这篇关于用细绳的sizeof行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!