简体   繁体   English

C中的typedef用于结构

[英]typedef in C for struct

If I have a struct such as: 如果我有一个结构,例如:

typedef struct bag {
  int test;
} *bag;

Then if a function consumes bag. 然后,如果一个函数消耗了包。 Let's say: 比方说:

int sample(bag *b) {
    b->test ...
}

I get the error that I made a request for member 'b' in something that is not a structure or union. 我收到我在不是结构或联合的情况下请求成员“ b”的错误。 How do I fix this? 我该如何解决? I could cast b to a (struct bag *) but that seems unreasonable. 我可以将b强制转换为(struct bag *),但这似乎是不合理的。

You just defined the type bag to be a pointer to the type struct bag . 您刚刚将type bag定义为指向 struct bag指针 Thus, when you make a variable of type bag *b , you are effectively creating a variable of type struct bag** . 因此,当您创建bag *b类型的变量时,实际上就是在创建struct bag**类型的变量。 Either change your argument to be bag b , or do a double dereference for your member ( (*b)->test ). 将您的参数更改为bag b ,或者对您的成员进行双重取消引用( (*b)->test )。

Edit As another poster mentioned, you probably meant typedef struct bag { ... } bag , then your original code will compile. 编辑正如另一位发帖人所述,您可能是用typedef struct bag { ... } bag ,然后将编译原始代码。

You have to decide: Either bag is the name for a pointer to the struct, or bag is a name for the struct: Probably you meant 您必须决定:bag是指向该结构的指针的名称,或者bag是该结构的名称:可能是您的意思

typedef struct bag {
   int test;
} bag;

Then your code compiles. 然后您的代码进行编译。

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

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