gpt4 book ai didi

c - C 中的 NUL 字符和静态字符数组/字符串文字

转载 作者:行者123 更新时间:2023-11-30 20:21:15 25 4
gpt4 key购买 nike

我知道在 C 中字符串以 NUL '\0' 字节终止。但是,我无法弄清楚为什么字符串文字中的 0 的行为与在堆栈上创建的 char 数组中的 0 的行为不同。检查文字中的 NUL 终止符时,数组中间的零不会被如此处理。

例如:

#include <stdio.h>
#include <string.h>
#include <sys/types.h>

int main()
{

/* here, one would expect strlen to evaluate to 2 */
char *confusion = "11001";
size_t len = strlen(confusion);
printf("length = %zu\n", len); /* why is this == 5, as opposed to 2? */



/* why is the entire segment printed here, instead of the first two bytes?*/
char *p = confusion;
while (*p != '\0')
putchar(*p++);
putchar('\n');



/* this evaluates to true ... OK */
if ((char)0 == '\0')
printf("is null\n");


/* and if we do this ... */
char s[6];
s[0] = 1;
s[1] = 1;
s[2] = 0;
s[3] = 0;
s[4] = 1;
s[5] = '\0';

len = strlen(s); /* len == 2, as expected. */
printf("length = %zu\n", len);

return 0;
}

输出:

 length = 5
11001
is null
length = 2

为什么会出现这种情况?

最佳答案

变量“confusion”是指向文字字符串的字符的指针。所以内存看起来像这样

 [11001\0]

因此,当您打印变量“confusion”时,它将打印所有内容,直到第一个空字符(由\0 表示)。
11001 中的零不为空,它们是文字零,因为它用双引号引起来。

但是,在变量 's' 的 char 数组赋值中,您将十进制值 0 赋给字符变量。当您这样做时,ASCII 十进制值 0(即 NULL 字符的 ASCII 字符值)将被分配给它。所以字符数组看起来就像在内存中

  [happyface, happyface, NULL]

ASCII 字符 happyface 的 ASCII 十进制值为 1。因此,当您打印时,它将打印直到第一个 NULL 为止的所有内容,因此strlen 为 2。

这里的技巧是理解当十进制值分配给字符变量时真正分配给它的是什么。

试试这个代码:

 #include <stdio.h>

int
main(void)
{
char c = 0;

printf( "%c\n", c ); //Prints the ASCII character which is NULL.
printf( "%d\n", c ); //Prints the decimal value.

return 0;

}

关于c - C 中的 NUL 字符和静态字符数组/字符串文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43383444/

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