Search code examples
c++arraysflexible-array-member

Using the struct itself in the definition of struct in C++


I want to implement a simple tree struct in C++, like:

struct node{
    ....
    node* parent;
    node[]* children;
    ....
};

but the compiler reported an error (both CLang++ and G++)

error: expected unqualified-id before '[' token
node[]* child;
    ^

error: expected ',' or '...' before '*' token
node(node[]* c): : child = c; {}
           ^

something like this

BTW, I'm using the -std=c++11 flag for some C++ 11 feature

any help is appriciated


Solution

  • Size of struct is compile time constant. If you give an array of size to be determined later, it is an error. Either give some size (For ex 2 in case of binary tree) or use pointer to node * to store an array or pointer (children) or use some builtin container (for ex std::vector, std::array)