我写了这段代码:
Resident_x * infos_shorted;
Residents=6;
infos_shorted=(Resident_x *)malloc(Residents*(sizeof(Resident_x)));
i=0;
while ((infos_shorted+i)!=NULL){
printf ("%d\n", i);
i++;
}
尽管有人会期望我分配了 6 个内存位置,但当我运行它时,它会一直打印 i ,直到我手动终止它。
这就是我为找到主要问题的答案所做的事情:
我写的是:
Resident_x * infos_shorted;
Residents=6;
infos_shorted[i].height[8]=7;
infos_shorted=(Resident_x *)malloc(Residents*(sizeof(Resident_x)));
for (i=0; i<=Residents+4; i++){
printf ("%d %d\n", infos_shorted[i].height, i);
}
我正确打印了 infos_shorted[i].height[8] 。怎么样;
最佳答案
while ((infos_shorted+i)!=NULL){
一旦i > Residents
,你就会有未定义的行为。尽管如此,infos_shorted + i
很可能会计算出 infos_shorted
值后面的 i*sizeof(Resident_x)
个字节的地址。没有理由期望这样的地址是空指针(直到它换行,但这是更多未定义的行为)。
关于c - c 中意外的数组分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16155284/