简体   繁体   English

如何在C中重新分配结构内部数组的大小?

[英]how to reallocate the size of an array inside a structure in C?

This is the code that I have to dynamically declaring an array inside a structure. 这是我必须动态声明结构内部数组的代码。 I am dynamically allocating the array list with a size called 'capacity'. 我正在动态分配大小为“容量”的数组列表。 At a later point in my program, I want to increase the size of my array and re-allocate it. 在程序的后面,我想增加数组的大小并重新分配它。 How do I go about it? 我该怎么办?

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

wrapper function to declare the array present inside the structure 包装函数,用于声明结构内部存在的数组

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

calling the wrapper function 调用包装函数

struct mystruct *h1 = mystruct_init();

My question is, how do I use the realloc function to increase the size of list (double the value of capacity)? 我的问题是,如何使用realloc函数增加列表的大小(将容量的值增加一倍)? It would be really nice if someone could help me out. 如果有人可以帮助我,那将非常好。

assume you have int oldsize : 假设你有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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM