gpt4 book ai didi

c - sizeof 与字符串的行为

转载 作者:太空狗 更新时间:2023-10-29 15:24:13 25 4
gpt4 key购买 nike

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

http://ideone.com/kw23IV

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

在 Debian 7.4 上使用 GCC

最佳答案

字符串文字的大小是其中的字符数,包括添加的尾随空字节。如果字符串中嵌入了空值,则它们无关紧要;他们被计算在内。它与 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_t 的正确格式化类型限定符是z,因为它是无符号的,ud 更合适,因此 "%zu\n" 我使用的格式。

关于c - sizeof 与字符串的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22749424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com