简体   繁体   English

Typedef结构混乱中的指针

[英]Pointer in typedef struct confusion

I am trying to define a typedef struct as follows: 我试图定义一个typedef结构,如下所示:

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: 为什么不使用struct node* child[2*MIN_DEGREE]而不是如下声明结构:

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 谢谢

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 * . 您不能在结构体中使用BNODEPTR ,因为它要么根本不作为类型存在,要么在结构体的大括号后定义之后才出现,或者(更糟糕的是)它完全引用了另一种类型*

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. 还有另一种说法认为BNODEPTR是邪恶的,您应该只使用BNODEBNODE * ,但这是一个样式问题,而不是技术问题。

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). 在C ++中,规则略有不同,您不需要typedef行(因此,从大括号中可以将Node称为类型)。

* 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! *仅当原始BNODEPTR在外部作用域中定义并且该作用域出现在函数内部时,才会发生这种情况,但是当发生这种情况时,确实会造成混淆!

Instead of using struct node* child[2*MIN_DEGREE] why can't I declare the struct as follows: BNODEPTR child[2*MIN_DEGREE]; 为什么不使用struct node* child[2*MIN_DEGREE]声明结构,如下: BNODEPTR child[2*MIN_DEGREE]; ?

At that point, compiler (yet) does not know what the symbol BNODEPTR is. 到那时,编译器(尚未)不知道符号BNODEPTR是什么。

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

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