【问题标题】:C programming: Accessing pointers in a UnionC 编程:访问联合中的指针
【发布时间】:2017-09-26 08:52:47
【问题描述】:

有人可以帮我访问联合中的指针吗,我不断收到一个 [Error] 无效类型参数“->”(有“结构节点”)。这是一个包含我的数据结构的 sn-p:

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;
}

如果有人能指出我如何在联合中访问我的指针,那就太好了。谢谢大家。

【问题讨论】:

  • 您有多个错误。对于初学者,temp 在取消引用时指向哪里?
  • typedef struct twoThree{ ... }*TTT -- 在大多数情况下,typedef 指针是个坏主意。
  • 至于你的问题,U.iNode不是指向结构的指针,它是一个结构object,因此你不应该使用箭头操作符-&gt;来访问它的成员。
  • 在不相关的注释中,请不要在代码 sn-ps 中使用 markdown 格式。

标签: c pointers structure unions


【解决方案1】:
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*/**
        }

此部分存在结构不匹配,因此显示错误。

说明: T 和 temp 指向两个两个结构,在 elseif 情况下,访问 (*T)->U.leaf.key,这意味着该结构包括(indicator indic 和 struct Leaf)。 在相同的情况下 (*temp)->U.iNode.key1 被访问,这意味着 temp 指向类型的结构(indicator indic 和 struct iNode)。这种不匹配是错误的原因。由于 union 将允许一次单独存在 struct iNode 或 struct Leaf。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    • 2023-01-19
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多