使用C调整数组大小

Gar*_*ary 19 c memory arrays dynamic

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

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

Del*_*ani 30

首先创建数组:

structName ** sarray = (structName **) malloc(0 * sizeof(structName *));
Run Code Online (Sandbox Code Playgroud)

始终分别跟踪大小:

size_t sarray_len = 0;
Run Code Online (Sandbox Code Playgroud)

增加或截断:

sarray = (structName **) realloc(sarray, (sarray_len + offset) * sizeof(structName *));
Run Code Online (Sandbox Code Playgroud)

然后设置大小:

sarray_len += offset;
Run Code Online (Sandbox Code Playgroud)

乐于助人,希望有所帮助.

  • 通过编写`structName**sarray = NULL;`可以大大改善第一行.使用带有空指针的`realloc`是明确定义的. (9认同)
  • 注意,`malloc(0)`具有实现定义的结果;它可能会返回NULL或永远不会被取消引用的有效指针(但可以传递给free()或realloc())。 (2认同)

M.M*_*M.M 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);
}
Run Code Online (Sandbox Code Playgroud)

乘法是因为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;
}
Run Code Online (Sandbox Code Playgroud)

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


Pav*_*sky 8

来自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;
}
Run Code Online (Sandbox Code Playgroud)

  • 我给了参考,这使它成为一个cookie,不是吗? (10认同)