简体   繁体   English

C编程:访问联合中的指针

[英]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'). 有人可以帮我用联合访问指针吗,我不断收到[错误]无效类型参数'->'(具有'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). 说明:有两个由T和temp指向的结构,在elseif情况下(* T)-> U.leaf.key被访问,这意味着该结构包括(指示符indic和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). 在相同情况下,将访问(* temp)-> U.iNode.key1,这意味着温度指向类型的结构(指示符indic和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. 由于联合将允许一次仅存在struct iNode或struct leaf。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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