【问题标题】:how to reallocate the size of an array inside a structure in C?如何在C中的结构内重新分配数组的大小?
【发布时间】:2012-02-01 21:08:19
【问题描述】:

这是我必须在结构内动态声明数组的代码。我正在动态分配具有称为“容量”的大小的数组列表。在我的程序的稍后时刻,我想增加我的数组的大小并重新分配它。我该怎么办?

struct mystruct {
 int x;
 struct y **list;
};

用于声明结构中存在的数组的包装函数

struct mystruct *mystruct_init()
{
    struct mystruct *mystruct = calloc(1, sizeof(*mystruct));

    // loop through and allocate memory for each element in list
    mystruct->list = calloc(1, sizeof(struct y *) * mystruct->list_length);

    for (int i = 0; i < capacity; i++)
        mystruct->list[i] = calloc(1, sizeof(struct y));

    return mystruct;
}

调用包装函数

struct mystruct *h1 = mystruct_init();

我的问题是,如何使用 realloc 函数来增加列表的大小(容量值的两倍)?如果有人可以帮助我,那就太好了。

【问题讨论】:

标签: c


【解决方案1】:

假设你有int oldsize:

struct y **newlist=realloc(h1->list,oldsize*2*sizeof(struct y*));
if (!newlist) return -1;//error
h1->list=newlist;
int i;
for (i=oldsize;i<2*oldsize;i++) h1->list[i]=calloc(1,sizeof(struct y));

【讨论】:

  • @asaeir :我在重新分配行上收到此错误 ** 检测到 glibc *** ./compareDocs: realloc(): invalid next size: 0x0000000000603030 ***.....知道这可能是什么吗?
猜你喜欢
  • 2022-01-04
  • 2016-02-29
  • 2019-02-02
  • 2014-05-31
  • 2018-11-03
  • 2019-06-03
  • 1970-01-01
  • 2014-01-23
  • 2015-06-22
相关资源
最近更新 更多