c - 多次使用 realloc()

标签 c memory dynamic allocation realloc

下列哪一项更可取

file=fopen(argv[1],"r");
arr=(unsigned int *)malloc(4);

while(!feof(file))
{
  ++arr_size;
  arr=(unsigned int *)realloc(arr,arr_size*sizeof(unsigned int)
  fscanf(file,"%u\n",&arr[arr_size-1]);
}
fclose(file);

或者这个

arr=(unsigned int *)malloc(some_size*sizeof(unsigned int));
file=fopen(argv[1],"r");
arr=(unsigned int *)malloc(4);

while(!feof(file))
{
  ++arr_size;
  fscanf(file,"%u\n",&arr[arr_size-1]);
}
fclose(file);

最佳答案

为什么不采用第三种方法 - 计算出打开文件时需要多少内存?

关于c - 多次使用 realloc(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7106022/

相关文章:

c - C 中的链表,如何修复预期标识符错误?

c - 需要对程序输出的解释。

c - 在c中获取特定格式的输入

c shell 陷入死循环

c++ - 错误[Lp001]内存不足,但我不应该这样做

memory - 为什么将内存区域标记为非缓存?

c++ - 如何使用自定义 STL vector 类避免智能指针 delete[] 异常?

mysql - 动态添加mysql表列

c# - GridView:Columns.Insert() 导致我的数据在回发时消失,但 Columns.Add() 工作正常吗?

android - 动态 TableLayout Android