gpt4 book ai didi

C奇怪的int数组指针

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

int *array; //it allocate a pointer to an int right?
array=malloc(sizeof(int); //allocate the space for ONE int right?
scanf("%d", &array[4]); //must generate a segmentation fault cause there is not allocated space enough right?
printf("%d",array[4]); //it shouldn't print nothing...

但它打印出 4!为什么?

最佳答案

在 C 中读取或写出数组末尾会导致未定义的行为,这意味着任何事情都可能发生。它可能会使程序崩溃,或格式化硬盘,或导致计算机着火。在您的情况下,碰巧这种情况非常好,可能是因为 malloc 出于效率原因填充了分配的内存的长度(或者可能是因为您正在浪费malloc 稍后要使用)。然而,这根本不便携,不能保证正常工作,而且是一场即将发生的灾难。

希望这有帮助!

关于C奇怪的int数组指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24222592/

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