简体   繁体   中英

C programming: Accessing pointers in a Union

Can someone please help me with accessing pointers with in a union, I keep getting an [Error] invalid type argument of '->'(have 'struct node'). Here's a snippet with my data structure in it:

typedef enum{LEAF,INODE}indicator;

typedef struct twoThree{
    indicator indic;
    union{
        struct L{
            int key;
        }leaf;  
        struct node{
            int key1,key2;
            struct twoThree *LC,*MC,*RC;
        }iNode;
    }U;
}*TTT;


void insertElem(TTT *T, int elem)
{
    TTT *temp;

    if(*T==NULL){
        *T=initTree();
        (*T)->indic = LEAF;
        (*T)->U.leaf.key = elem;
    }else if((*T)->indic == LEAF){
        if(elem < (*T)->U.leaf.key){
            (*temp)=initTree();
            (*temp)->indic = INODE;
            (*temp)->U.iNode.key1 = elem;

            **(*temp)->U.iNode->LC = *T; /*This is my problem"->LC" part*/**
        }
    }
}

TTT initTree()
{
    TTT T;
    T=(TTT)malloc(sizeof(struct twoThree));
    if(T!=NULL){
        printf("Initialization of tree was successful.\n");
    }else{
        printf("Failed initialization of tree.\n");
    }

    return T;
}

If anyone could point out on how I accessed my pointer within the union, that would be great. Thanks guys.

else if((*T)->indic == LEAF){
        if(elem < (*T)->U.leaf.key){
            (*temp)=initTree();
            (*temp)->indic = INODE;
            (*temp)->U.iNode.key1 = elem;

            **(*temp)->U.iNode->LC = *T; /*This is my problem"->LC" part*/**
        }

In this section there is a structure mismatch, Hence it is showing the error.

Explanation: There are two two structures pointed by T and temp, In the elseif case (*T)->U.leaf.key is accessed which means the structure includes (indicator indic and struct leaf). In the same case (*temp)->U.iNode.key1 is accessed which means temp points to structure of type (indicator indic and struct iNode). This mismatch is the reason for the ERROR. As union will allow the existence either struct iNode or struct leaf alone at a time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM