2014-03-30 34 views
2
‪#‎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; 
} 

输出的sizeof:行为与字符串

5 
6 
6 
7 
6 
7 

http://ideone.com/kw23IV

谁能解释与字符串的这种行为?

在Debian 7.4

+1

你在问为什么它不停在'\ 0'?只是因为它报告存储在内存中的常量的大小。 Sizeof不关心它是否为空字符串。它只是看到一个静态大小的字符数组。 – Dave

+2

'sizeof'返回'size_t'类型的值;您将该值传递给'printf()'说明符'“%d”',它需要'int'。 'size_t'和'int'不必具有相同的表示形式:您可能会得到奇怪的结果。我建议你使用C99的''%zu''指定符或者从'sizeof'中强制返回值:'printf(“%d \ n”,(int)sizeof“hello”);'' – pmg

回答

5

字符串文字的大小是在它的字符包括被添加的后空字节的数目。如果在字符串中嵌入空值,它们是无关紧要的;他们被计算在内。它与strlen()无关,只是如果文字不包含嵌入的空值,则为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'只是一个更一般的八进制常量的特例。

注意sizeof()计算结果为size_t类型的值,并且在C99和C11上的正确的格式类型限定符size_tz,并且因为它是无符号的,ud更合适,因此"%zu\n"格式,我用。

2

文字字符串使用GCC正是以保持的所有字符所需的尺寸和一个额外的终止零字节的阵列。

所以,"hello"具有类型char[6]sizeof产量6.