Rn2dy
Rn2dy

Reputation: 4190

C union and struct question

I have a tree structure. The nodes would have a leaf node type and internal node type, so I defined these structures, so the internal node would be able to point to either internal nodes or leaf nodes. However, I am having trouble in accessing the child pointers, how can I do that, after all does my code make sense at all?

typedef struct leaf_node_t {
    int type;
    int key;
    int *data_ptr[2]; //This will point to real data.
} leaf_node_t;

typedef struct internal_node_t {
    int type;
    int key;
    typedef union{
        struct internal_node_t* iptrs[2];
        leaf_node_t* lptrs[2];
    } node_ptr;
} internal_node_t;

Upvotes: 2

Views: 856

Answers (3)

EMR
EMR

Reputation: 44

The typedef of node_ptr does not actually add a field to its enclosing struct. The following adds the fields first, and then follows up with the typedef. The other change I made was having the union represent a single pointer, leaving it to the struct that uses it to decide how many pointers it wants.

typedef struct internal_node_t{
   int type;
   int key;
   union node_ptr_t {
         struct internal_node_t* iptr;
         leaf_node_t* lptr;
   } node_ptr[2];
}internal_node_t;

typedef union node_ptr_t node_ptr_t;

Upvotes: 2

Karl Bielefeldt
Karl Bielefeldt

Reputation: 49128

Try this:

typedef struct leaf_node_t{
       int key;
       int *data_ptr[2];//this will point to real data
} leaf_node_t;

struct internal_node_t;

typedef union{
    struct internal_node_t* iptrs[2];
    leaf_node_t* lptrs[2];
} node_ptr;

typedef struct internal_node_t{
       int key;
       node_ptr node;
} internal_node_t;

int main()
{
    internal_node_t inode;

    leaf_node_t* leaf_node = inode.node.lptrs[0];
    return 0;
}

Alternately, if you don't actually need to use the union typedef anywhere else:

typedef struct leaf_node_t{
       int key;
       int *data_ptr[2];//this will point to real data
}leaf_node_t;

typedef struct internal_node_t{
       int key;
       union{
             struct internal_node_t* iptrs[2];
             leaf_node_t* lptrs[2];
       }node_ptr;
}internal_node_t;
int main()
{
    internal_node_t inode;

    leaf_node_t* leaf_node = inode.node_ptr.lptrs[0];
    return 0;
}

Upvotes: 2

xanatos
xanatos

Reputation: 111940

You should add a flag in the internal_node to know what is the node_ptr, if it's an internal_node_t or a leaf_node_t. Probably a int isInternal[2]; (after the key and before the typedef). if it's 0 the it's internal, if it's 1 then it's leaf_node_t. C language doesn't have a typeof or a GetType to know what type of memory is pointed by a pointer (and C++ has it only if you are compiling with the RTTI "option" activated)

Upvotes: 1

Related Questions