ZeroVash
ZeroVash

Reputation: 558

Realloc dynamic array inside of structure

I have a structure :

  struct Node{      

        struct Node* pointer[0];  
        int num; 
    } *current=NULL;

and then in function I trying to create children to node

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

The problem is that realloc give me error.

realloc(): invalid pointer:

So if it was c++ I can make a vector and just push back the element, but with c I need to reallocate the array of pointers. How can I reallocate the memory?

Upvotes: 1

Views: 585

Answers (1)

dave
dave

Reputation: 4922

I know this looks like a problem of realloc but your problem is using an array of size zero in the middle of a struct. See here for an explanation of zero length arrays in gcc, also called flexible array members in C99, and specifically:

Flexible array members may only appear as the last member of a struct that is otherwise non-empty.

Upvotes: 3

Related Questions