动态分配数组

时间:2015-02-08 07:07:02

标签: c arrays dynamic

我在C中尝试动态分配数组。这是我的代码:

#include<stdio.h> 
#include<stdlib.h> 
int main() 
{   
int *array=(int*)malloc(5*sizeof(int));     
array[7]=7;     
array[8]=5;     
printf("\n%d\t%d",array[7],array[8]); 
} 

我不明白为什么数组[7]被打印出来,以及为什么数组[8]没有。实际上在使用数组[8]时,程序在运行代码时停止响应。为什么会这样?当我声明大小为5的数组时,程序是否应该在数组[5]之后停止工作?

1 个答案:

答案 0 :(得分:1)

由于UB(Undefined Behaviour)这意味着任何都可能发生。您的程序可能会崩溃,出现分段错误,擦除硬盘或触发它,make demons fly out your nose等。在C中,don't cast the result of malloc。此外,free使用malloc后的内存{。}}。

相关问题