Behaviour of sizeof with string

送分小仙女□ 提交于 2019-12-19 21:42:29

问题


‪#‎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;
}

output:

5
6
6
7
6
7

http://ideone.com/kw23IV

Can anyone explain this behaviour with character strings?

Using GCC on Debian 7.4


回答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

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.

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.




回答2:


A literal character string is an array of exactly the size needed to hold all the characters and an extra terminating zero-byte.

So, "hello" has type char[6] and sizeof yields 6.



来源:https://stackoverflow.com/questions/22749424/behaviour-of-sizeof-with-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!