gpt4 book ai didi

c - 字符串终止符问题

转载 作者:太空宇宙 更新时间:2023-11-04 06:13:25 25 4
gpt4 key购买 nike

如果我输入这段代码,它会编译并运行(我使用 GCC)

#include<stdio.h>
int main()
{

char sentence[8]="September";

printf("The size of the array is %d \n",sizeof(sentence));

printf("The array is %s \n",sentence);
}

并给出输出

The size of the array is 8

The array is Septembe

这是如何运作的? C 需要一个字符串终止符来知道字符串已经结束。数组如何值 8 个字节的空间并知道在哪里停止?

最佳答案

通过将非 NUL 终止的字符串传递给 printf("%s"),您将调用未定义的行为

就其本质而言,结果是不确定的。它可能看起来“有效”(如您所见)。


正如其他人所解释的那样,可能发生的情况是您的字符串后恰好有一个零字节,这会阻止 printf 继续前进。但是,如果您要围绕该变量添加更多东西,您可能会看到不同的行为:

#include<stdio.h>

int main(void)
{
char sentence[8] = "September"; // NOT NUL TERMINATED!
char stuff[] = "This way is better";

printf("%s\n", sentence); // Will overrun sentence
return 0;
}

关于c - 字符串终止符问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51446150/

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