简体   繁体   中英

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. How do I fix this? I could cast b to a (struct bag *) but that seems unreasonable.

You just defined the type bag to be a pointer to the type struct bag . Thus, when you make a variable of type bag *b , you are effectively creating a variable of type struct bag** . Either change your argument to be bag b , or do a double dereference for your member ( (*b)->test ).

Edit As another poster mentioned, you probably meant typedef struct bag { ... } bag , then your original code will compile.

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

typedef struct bag {
   int test;
} bag;

Then your code compiles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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