【问题标题】:Resizing an array with C使用 C 调整数组大小
【发布时间】:2011-02-25 14:46:34
【问题描述】:

我需要在我正在制作的游戏中拥有一个结构数组 - 但我不想将数组限制为固定大小。有人告诉我有一种方法可以在需要时使用 realloc 使数组更大,但找不到任何可行的示例。

有人可以告诉我怎么做吗?

【问题讨论】:

标签: c arrays memory dynamic


【解决方案1】:

从创建数组开始:

structName ** sarray = (structName **) malloc(0 * sizeof(structName *));

始终单独跟踪尺寸:

size_t sarray_len = 0;

增加或截断:

sarray = (structName **) realloc(sarray, (sarray_len + offset) * sizeof(structName *));

然后设置大小:

sarray_len += offset;

很乐意提供帮助,希望对您有所帮助。

【讨论】:

  • structName ** sarray = NULL; 会大大改善第一行。将realloc 与空指针一起使用是明确定义的。
  • 注意malloc(0) 有实现定义的结果;它可能返回 NULL 或永远无法取消引用的有效指针(但可以传递给 free()realloc())。
  • 吹毛求疵:这并不管理“结构数组”,而是一个指向结构的指针数组。
  • 这不就是指针的大小吗? sizeof(structName *)不是sizeof(structName)吗?还有为什么我们需要一个双指针?
【解决方案2】:

realloc 函数可用于扩大或缩小数组。当数组增长时,现有条目保留其值,新条目未初始化。这可能会就地增长,或者如果不可能,它可能会在内存中的其他地方分配一个新块(在幕后,将所有值复制到新块并释放旧块)。

最基本的形式是:

// array initially empty
T *ptr = NULL;

// change the size of the array
ptr = realloc( ptr, new_element_count * sizeof *ptr );

if ( ptr == NULL )
{
    exit(EXIT_FAILURE);
}

乘法是因为realloc 需要多个字节,但您始终希望数组具有正确数量的元素。请注意,realloc 的这种模式意味着除了 ptr 的原始声明之外,您不必在代码中的任何地方重复 T

如果您希望您的程序能够从分配失败中恢复而不是执行exit,那么您需要保留旧指针而不是用 NULL 覆盖它:

T *new = realloc( ptr, new_element_count * sizeof *ptr );

if ( new == NULL )
{
    // do some error handling; it is still safe to keep using
    // ptr with the old element count
}
else
{
    ptr = new;
}

请注意,通过realloc 缩小数组实际上可能不会将内存返回给操作系统;内存可能继续由您的进程拥有,并可用于将来调用mallocrealloc

【讨论】:

    【解决方案3】:

    来自http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/

    /* realloc example: rememb-o-matic */
    #include <stdio.h>
    #include <stdlib.h>
    
    int main ()
    {
      int input,n;
      int count=0;
      int * numbers = NULL;
    
      do {
         printf ("Enter an integer value (0 to end): ");
         scanf ("%d", &input);
         count++;
         numbers = (int*) realloc (numbers, count * sizeof(int));
         if (numbers==NULL)
           { puts ("Error (re)allocating memory"); exit (1); }
         numbers[count-1]=input;
      } while (input!=0);
    
      printf ("Numbers entered: ");
      for (n=0;n<count;n++) printf ("%d ",numbers[n]);
      free (numbers);
    
      return 0;
    }
    

    【讨论】:

    • 我给出了参考,这使它成为一个cookie,不是吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-06
    • 2012-10-02
    • 1970-01-01
    • 2011-11-10
    相关资源
    最近更新 更多