【问题标题】:C: Expanding an array with mallocC: 使用 malloc 扩展数组
【发布时间】:2010-04-30 22:26:39
【问题描述】:

总的来说,我对 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;
}
  • 上面的例子应该清楚我想要完成什么。

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

【问题讨论】:

    标签: c arrays malloc


    【解决方案1】:

    使用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.
       }
    

    【讨论】:

    • x = realloc(x, newsize) 是等待发生的内存泄漏。
    • 好点。我更新了示例代码以处理重新分配失败。
    • myarray = myrealloced_array) 应该是 myarray = myrealloced_array; :)
    • 你不一定要先用malloc()进行分配——“如果ptr是空指针,realloc函数的行为就像指定大小的malloc函数”
    • 编程很难。 :)
    【解决方案2】:

    您想使用 realloc(正如其他发帖人已经指出的那样)。但遗憾的是,其他的海报并没有告诉你如何正确使用它:

    POINTER *tmp_ptr = realloc(orig_ptr, new_size);
    if (tmp_ptr == NULL)
    {
        // realloc failed, orig_ptr still valid so you can clean up
    }
    else
    {
        // Only overwrite orig_ptr once you know the call was successful
        orig_ptr = tmp_ptr;
    }
    

    您需要使用tmp_ptr,这样如果realloc 失败,您就不会丢失原始指针。

    【讨论】:

      【解决方案3】:

      不,你不能。一旦定义了堆栈上的数组,就无法更改它的大小:这就是固定大小的含义。或者是一个全局数组:从您的代码示例中不清楚myarray 的定义位置。

      您可以 malloc 一个 1000 元素的数组,然后使用 realloc 调整它的大小。这可以为您返回一个新数组,其中包含旧数组中数据的副本,但末尾有额外的空间。

      【讨论】:

        【解决方案4】:

        a) 您没有使用 malloc 来创建它,因此您无法使用 malloc 进行扩展。做:

          mystruct *myarray = (mystruct*)malloc(sizeof( mystruct) *SIZE);
        

        b) 使用 realloc (RTM) 使其更大

        【讨论】:

          猜你喜欢
          • 2015-10-11
          • 1970-01-01
          • 2021-10-14
          • 1970-01-01
          • 1970-01-01
          • 2013-03-31
          • 1970-01-01
          • 1970-01-01
          • 2015-07-02
          相关资源
          最近更新 更多