gpt4 book ai didi

c++ - 程序选择 '\0',即使它没有被提及——澄清

转载 作者:行者123 更新时间:2023-11-30 01:07:08 24 4
gpt4 key购买 nike

所以,我可以预测这个程序会做什么:

int main()
{
char d[] = {'h','e','l','l','o'};
const char *c = d;
std::cout << *c << std::endl;
while ( *c ) {
c = c + 1;
std::cout << *c << std::endl;
if ( *c == '\0' )
std::cout << "Yes" << std::endl;
}
return 0;
}

根据我的理解,代码不应该打印 Yes,因为字符数组 d[] 中没有 \0,所以这是这个程序正在挑选的垃圾值吗?我做空这段时间应该无限次运行。是吗?

最佳答案

这个问题的正确答案是程序表现出未定义的行为,因为它超出了数组的末尾。

将程序更改为使用字符串文字进行初始化会将行为更改为“始终打印 "Yes":

char d[] = "hello";

I short this while should run infinite times.

一旦未定义的行为发生,所有的赌注都会被取消。然而,程序通常设法在 d[] 之外的内存中找到一个零字节,此时它会打印 “Yes”,然后退出循环。

关于c++ - 程序选择 '\0',即使它没有被提及——澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45019224/

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