gpt4 book ai didi

c - 意外的 C 代码输出

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

这是我的 C 代码:

#include <stdio.h>


int main(){

int x[] = {6,1,2,3,4,5};
int *p=0;
p =&x[0];


while(*p!='\0'){

printf("%d",*p);
p++;
}

return 0;


}

运行时输出为 612345-448304448336

减号后的数字是什么?为什么我的代码给出这个数字?

最佳答案

永远不会满足条件 *p != '\0',它与 *p != 0 相同,因为您的数组不包含值 0 的元素,因此您会超出数组边界并进入未定义的行为

相反,您应该直接控制数组范围:

for (int const * p = x; p != x + sizeof(x)/sizeof(x[0]); ++p)  // or "p != x + 6"
{
printf("%d", *p);
}

关于c - 意外的 C 代码输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9648367/

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