C语言 用 C 调整数组大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2937409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:31:49  来源:igfitidea点击:

Resizing an array with C

carraysmemorydynamic

提问by Gary

I need to have an array of structs in a game I'm making - but I don't want to limit the array to a fixed size. I'm told there is a way to use realloc to make the array bigger when it needs to, but can't find any working examples of this.

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

Could someone please show me how to do this?

有人可以告诉我如何做到这一点吗?

回答by Delan Azabani

Start off by creating the array:

首先创建数组:

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

Always keep track of the size separately:

始终单独跟踪大小:

size_t sarray_len = 0;

To increase or truncate:

增加或截断:

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

Then set the size:

然后设置大小:

sarray_len += offset;

Happy to help and hope that helps.

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

回答by M.M

The reallocfunction can be used to grow or shrink an array. When the array grows, existing entries retain their value and new entries are uninitialized. This may either grow in-place, or if that was not possible, it may allocate a new block elsewhere in memory (and behind the scenes, copy all the values over to the new block and free the old block).

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

The most basic form is:

最基本的形式是:

// 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);
}

The multiplication is because reallocexpects a number of bytes, but you always want your array to have the right number of elements. Note that this pattern for reallocmeans you do not have to repeat Tanywhere in your code other than the original declaration of ptr.

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

If you want your program to be able to recover from an allocation failure instead of doing exitthen you need to retain the old pointer instead of overwriting it with NULL:

如果您希望您的程序能够从分配失败中恢复而不是这样做,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;
}

Note that shrinking an array via reallocmay not actually return memory to the operating system; the memory may continue to be owned by your process and available for future calls to mallocor realloc.

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

回答by Pavel Radzivilovsky

From http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/

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