c - 使用 malloc 扩展数组

标签 c arrays malloc

总的来说,我对 malloc 和 C 有点陌生。我想知道如何在需要时使用 malloc 扩展固定大小数组的大小。

例子:

#define SIZE 1000
struct mystruct
{
  int a;
  int b;
  char c;
};
mystruct myarray[ SIZE ];
int myarrayMaxSize = SIZE;
....
if ( i > myarrayMaxSize )
{
   // malloc another SIZE (1000) elements
   myarrayMaxSize += SIZE;
}
  • 上面的例子应该清楚我想要完成什么。

(顺便说一句:我写的解释器需要这个:使用固定数量的变量,如果需要更多,只需动态分配它们)

最佳答案

使用realloc , 但你必须先用 malloc 分配数组。在上面的示例中,您将它分配到堆栈上。

   size_t myarray_size = 1000;
   mystruct* myarray = malloc(myarray_size * sizeof(mystruct));

   myarray_size += 1000;
   mystruct* myrealloced_array = realloc(myarray, myarray_size * sizeof(mystruct));
   if (myrealloced_array) {
     myarray = myrealloced_array;
   } else {
     // deal with realloc failing because memory could not be allocated.
   }

关于c - 使用 malloc 扩展数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2748036/

相关文章:

c++ - 内存对齐高于最大对齐 alignas malloc

c - 释放树中动态分配的内存

c - C 中的 Malloc 语法

c - 我似乎无法理解如何将我的 scanf 限制为仅 float

c - 警告 : comparison between pointer and integer

c - 在 C 中将子 pid 打印到标准输出

javascript - 如何使用 Parse.com 中的云代码将UniqueObject 添加到非当前用户类?

java - 显示哪个月的降雨量最低 - arrays java

javascript - 如何使该对象成为数组?

c - 这个 sizeof 把戏在做什么?