我有一个结构:
struct Node{
struct Node* pointer[0];
int num;
} *current=NULL;然后在函数中,我尝试创建节点的子节点。
void AddChild(struct Node *node) {
uint8_t n=2; // number of add children
for(uint8_t i=n; i-->0;){
struct Node* leaf=(struct Node*)malloc(sizeof(struct Node)); //allocate memory to child
struct Node* tmp=(struct Node*)realloc(node->pointer,(++node->num)*sizeof(struct Node*)); //reallocate memory for dynamic array mistake
if (!tmp)
printf("Error in memory alocation\n");
node->pointer[node->num]=leaf;
}
}问题是,realloc给了我错误。
realloc():无效指针:
因此,如果是c++,我可以创建一个向量并将元素向后推,但是使用c时,我需要重新分配指针数组。我怎样才能重新分配记忆?
发布于 2017-01-24 03:35:57
我知道这看起来像是realloc的问题,但是您的问题是在struct中间使用大小为零的数组。有关在这里中使用gcc中的零长度数组(在C99中也称为柔性数组成员)的解释,请参阅C99,特别是:
灵活的数组成员可能只显示为结构的最后一个成员,否则是非空的。
https://stackoverflow.com/questions/41819499
复制相似问题