【问题标题】:How to realloc an array of structs如何重新分配结构数组
【发布时间】:2017-08-21 04:03:38
【问题描述】:

使用 c,我尝试将内容输入到结构数组中,一旦该数组被填充,将数组的大小加倍并继续使用 realloc。

我知道已经有人问过这样的几个问题,但我希望有人能解释清楚,因为我没有像这些问题那样创建数组并且有点困惑。

我有一个结构

struct Data {
    // Some variables
}

并使用

初始化数组
struct Data entries[100];
int curEntries = 100;
int counter = 1; // index, I use (counter - 1) when accessing

要重新分配,我目前正在使用

if(counter == curEntries){  // counter = index of array, curEntries = total
    entries = realloc(entries, curEntries * 2);
}

我知道我需要将 realloc 强制转换为正确的东西?我只是不确定我要如何或将其转换为什么,所以我目前没有任何东西,这当然会给我错误“赋值给具有数组类型的表达式”

谢谢!

【问题讨论】:

  • 您正在处理的类型是struct Data。尝试像这样投射到它:entries = (struct Data *) realloc((struct Data *) entries, curEntries * 2);
  • 此外,我已经看到这通常与 malloc 配对(在堆而不是堆栈中分配)。你为什么不使用它?
  • 数组不能是reallocstruct Data entries[100]; --> struct Data *entries = malloc(100 * sizeof *entries);
  • 嗯,那个铸造不起作用,但下面的答案似乎是这样做的方法。 . .至于使用malloc,我不确定第一次初始化时有什么区别,他们不做同样的事情吗?

标签: c arrays pointers memory struct


【解决方案1】:
struct Data entries[100];// memory is already allocated to this

您需要将entries 声明为如下指针:

struct Data *entries=NULL;
entries = malloc(curEntries  * sizeof(struct Data));
//When its time to reallocate
entries = realloc(entries, (curEntries * 2 * sizeof(struct Data)));

【讨论】:

  • 成语old_ptr = realloc(old_ptr, new_size) 是等待发生的内存泄漏。正确的成语是new_ptr = realloc(old_ptr, new_size); if (new_ptr == NULL) { …handle out of memory error… } old_ptr = new_ptr;
  • 你能详细说明一下内存泄漏吗?
  • @programmerc3981143 realloc() 可以在失败时返回 NULL。在这种情况下,您将使用NULL 覆盖指向动态分配内存的指针。因此,您以后无法free()。这可以通过将realloc() 的结果存储在一个新指针中来防止这种情况发生,并且只有在您检查它实际上不是NULL 之后才将其分配给旧指针。
猜你喜欢
  • 2011-09-04
  • 2021-07-15
  • 2019-02-02
  • 2014-05-31
  • 2018-06-28
  • 1970-01-01
  • 2019-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多