简体   繁体   English

在不阻止关键字struct的情况下,对结构进行typedef

[英]typedef a struct without preventing the keyword struct

Suppose this scheme: 假设此方案:

/* avl.c */

typedef struct avl {
    void *data;
    int height;
    struct avl *left, *right;
} node;

/* avl.h */

struct avl; /* opaque */

I want to use: 我要使用:

struct node *root;

instead of 代替

node *root;

in avl.c, but for now the best I have found is: 在avl.c中,但目前我发现的最好结果是:

struct avl {
    void *data;
    int height;
    struct avl *left, *right;
};

#define node avl

Another way? 其他方式?

Then you should remove the typedef : 然后,您应该删除typedef

struct node{
    void *data;
    int height;
    struct node *left, *right;
} 

Without using the preprocessor, you must give the struct and the typedef the same name for that to work, eg 在不使用预处理器的情况下,必须给struct和typedef使用相同的名称,例如,

  typedef struct node {
        void *data;
        int height;
        struct node *left, *right;
    } node;

So now struct node and node is the same thing. 所以现在struct nodenode是同一回事。

There is no other way than using macros to do that. 除了使用宏之外,别无其他方法。 The reason is that struct tags have their own namespace . 原因是struct标记具有自己的名称空间 Different names in the tag namespace always refer to different types, even if the structs contain the same member types. 标记名称空间中的不同名称始终引用不同的类型,即使结构包含相同的成员类型。 Proper aliasing of types can only be done with typedefs, which are defined to be aliases and not separate types. 正确的类型别名只能使用typedef定义,typedef被定义为别名而不是单独的类型。

struct avl {
    void *data;
    int height;
    struct avl *left, *right;
};

typedef struct alv node;

struct avl* ptr1; //valid
avl* ptr1; //not valid
struct node* ptr2;  //valid
node* ptr3;  //also valid

That forces you to use struct avl , that doesn't force you to use struct node , but you can if you want to. 那会迫使您使用struct avl ,而不会强迫您使用struct node ,但是如果您愿意的话,也可以。

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

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