Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C语言中,如何在结构内部重新分配数组的大小?_C - Fatal编程技术网

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

在C语言中,如何在结构内部重新分配数组的大小?,c,C,这是我必须在结构中动态声明数组的代码。我正在动态分配数组列表,其大小称为“容量”。在程序的稍后阶段,我想增加数组的大小并重新分配它。我该怎么做呢 struct mystruct { int x; struct y **list; }; 包装函数来声明结构中存在的数组 struct mystruct *mystruct_init() { struct mystruct *mystruct = calloc(1, sizeof(*mystruct)); // loop thr

这是我必须在结构中动态声明数组的代码。我正在动态分配数组列表,其大小称为“容量”。在程序的稍后阶段,我想增加数组的大小并重新分配它。我该怎么做呢

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

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

假设你有
intoldsize

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));
struct y**newlist=realloc(h1->list,oldsize*2*sizeof(struct y*));
如果(!newlist)返回-1//错误
h1->list=newlist;
int i;
for(i=oldsize;ilist[i]=calloc(1,sizeof(struct y));

@SethCarnegie您的编辑删除了一个所需的括号。@直到呜呜声,修复了,你know@asaeir:我在重新分配行**glibc detected***./compareDocs:realloc():无效的下一个大小:0x00000000000603030***…知道这是怎么回事吗?
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));