数组的动态分配
Dynamic allocation of array
我正在尝试在 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]);
}
我不明白为什么 array[7] 被打印出来,而 array[8] 却没有。实际上在使用数组 [8] 时,程序停止响应 运行 代码。为什么会这样?当我声明大小为 5 的数组时,程序是否应该在数组 [5] 本身之后停止工作?
因为UB(Undefined Behaviour) which means that anything can happen. Your program might crash, give a segmentation fault, wipe your hard disk or set fire to it , make demons fly out your nose etc . And In C, don't cast the result of malloc。此外,free
您在使用后 malloc
编辑的记忆。
我正在尝试在 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]);
}
我不明白为什么 array[7] 被打印出来,而 array[8] 却没有。实际上在使用数组 [8] 时,程序停止响应 运行 代码。为什么会这样?当我声明大小为 5 的数组时,程序是否应该在数组 [5] 本身之后停止工作?
因为UB(Undefined Behaviour) which means that anything can happen. Your program might crash, give a segmentation fault, wipe your hard disk or set fire to it , make demons fly out your nose etc . And In C, don't cast the result of malloc。此外,free
您在使用后 malloc
编辑的记忆。