[英]Errors when making a dynamic C array of structs
I have a struct called Collection
:我有一个名为
Collection
的结构:
typedef struct collection {
char *type;
char *arg;
} *Collection;
And I would like to have a dynamic array of this struct (or rather, of pointers to instances of this struct).我想要一个这个结构的动态数组(或者更确切地说,是指向这个结构实例的指针)。 This is what I tried:
这是我尝试过的:
Collection *rawCollections = malloc(0);
int colCounter = 0;
while (i < argc) {
Collection col = malloc(sizeof(Collection));
// code to fill in Collection
rawCollections = realloc(rawCollections, sizeof(rawCollections) + sizeof(Collection));
rawCollections[colCounter] = col;
colCounter++;
}
My reasoning is that we will add sizeof(Collection)
to the array each time I need to add another one.我的理由是,每次需要添加另一个数组时,我们都会将
sizeof(Collection)
添加到数组中。 I am getting these errors, and I am not sure why:我收到这些错误,我不知道为什么:
realloc(): invalid next size
Aborted (core dumped)
You must compute the new size for the array by multiplying the size of the array element (a pointer to a struct collection
) by the new number of elements ( colCounter + 1
).您必须通过将数组元素的大小(指向
struct collection
的指针)乘以新的元素数 ( colCounter + 1
) 来计算数组的新大小。
Note also how confusing it is to hide pointers behind typedefs: sizeof(Collection)
is not the size of the structure.还要注意在 typedef 后面隐藏指针是多么令人困惑:
sizeof(Collection)
不是结构的大小。
Here is a modified version:这是一个修改后的版本:
struct collection **rawCollections = NULL; // no need for `malloc(0)`
int colCounter = 0;
while (i < argc) {
struct collection *col = malloc(sizeof(*col));
// code to fill in Collection
rawCollections = realloc(rawCollections, sizeof(*rawCollections) * (colCounter + 1));
rawCollections[colCounter] = col;
colCounter++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.