Question

I am trying to define a typedef struct as follows:

typedef struct node{
    int keys[2*MIN_DEGREE-1];
    struct node* child[2*MIN_DEGREE];
    int numkeys;
    int isleaf;
} BNODE,*BNODEPTR;

Instead of using struct node* child[2*MIN_DEGREE] why can't I declare the struct as follows:

typedef struct node{
    int keys[2*MIN_DEGREE-1];
    BNODEPTR child[2*MIN_DEGREE];
    int numkeys;
    int isleaf;
} BNODE,*BNODEPTR;

I am little confused as to how the compiler resolves structs that has nested pointers to the same type. It will be great somebody helps me clear this up.

Thanks

Était-ce utile?

La solution

You can't use BNODEPTR in the body of the structure like that because it either doesn't exist as a type at all until after the definition after the close brace of the structure body, or (worse) it refers to a different type altogether*.

You could use:

typedef struct node BNODE, *BNODEPTR;

struct node
{
    int keys[2*MIN_DEGREE-1];
    BNODEPTR child[2*MIN_DEGREE];
    int numkeys;
    int isleaf;
};

And there's another whole argument that says BNODEPTR is evil and you should only use BNODE and BNODE *, but that's a style issue, not a technical one.

Were it my code, it would probably be more like:

typedef struct Node Node;

struct Node
{
    int   keys[2*MIN_DEGREE-1];
    Node *child[2*MIN_DEGREE];
    int   numkeys;
    int   isleaf;
};

In C++, the rules are slightly different and you would not need the typedef line (so Node would be known as a type from the open brace).

* This can only happen if the original BNODEPTR is defined at an outer scope and this one appears inside a function, but when it happens, it is really confusing!

Autres conseils

Instead of using struct node* child[2*MIN_DEGREE] why can't I declare the struct as follows: BNODEPTR child[2*MIN_DEGREE];?

At that point, compiler (yet) does not know what the symbol BNODEPTR is.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top