1

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?

2
  • 1
    struct Node* pointer[0];--> struct Node **pointer; and Rewrite according to this change. Commented Jan 24, 2017 at 3:38
  • 1
    node->pointer is not a pointer; furthermore, the pointer you pass to realloc must be a pointer that was allocated with malloc/realloc. Commented Jan 24, 2017 at 3:38

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.