【问题标题】:Dynamic allocation of array动态分配数组
【发布时间】:2015-02-08 07:07:01
【问题描述】:

我正在尝试在 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] 本身之后停止工作吗?

【问题讨论】:

  • 您的数组仅来自array[0] to array[4]
  • 如果你的数组只有 5 个元素,你为什么要搞乱第 8 和第 9 个元素?另外,不要转换malloc()的返回值。

标签: c arrays dynamic


【解决方案1】:

因为UB(Undefined Behaviour) 这意味着任何事情都可能发生。您的程序可能会崩溃、出现分段错误、擦除硬盘或着火,make demons fly out your nose 等。在 C 中,don't cast the result of malloc。另外,free 使用后您拥有的内存 malloced。

【讨论】:

  • 感谢您的回复。我试过 int array=malloc(sizeof(int)*5 );它给了我编译错误-从 void 到 int* 的无效转换
  • 你需要int* array 而不是int array。另外,您使用的是哪个编译器?我认为它是 C++ 编译器,而不是 C 编译器。
  • 这就是我使用的int * array=malloc(sizeof(int)*5),不知道为什么评论中没有显示*。 M 使用 Dev-C++。
  • 你确定你是用 C 编译而不是 C++ 编译器吗?我从来没有使用过 Dev C++...
猜你喜欢
  • 2020-03-06
  • 2020-09-13
  • 2015-03-09
  • 2012-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多