使用C调整数组大小

时间:2010-05-30 03:25:21

标签: c arrays memory dynamic

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

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

3 个答案:

答案 0 :(得分:29)

首先创建数组:

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

始终分别跟踪大小:

size_t sarray_len = 0;

增加或截断:

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

然后设置大小:

sarray_len += offset;

乐意帮助并希望有所帮助。

答案 1 :(得分:12)

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的此模​​式表示您不必在代码中的任何位置重复T,而不是ptr的原始声明。

如果您希望程序能够从分配失败中恢复而不是执行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

答案 2 :(得分:6)

来自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;
}