简体   繁体   中英

Pointers in typedef structs

I have the code:

typedef struct foo *bar;

struct foo {
    int stuff
    char moreStuff;
}

Why does the following give an incompatible pointer type error?

foo Foo;
bar Bar = &Foo;

To my knowledge, bar should be defined as a pointer to foo , no?

The complete code should look like

typedef struct foo *bar;

typedef struct foo {  //notice the change
    int stuff;
    char moreStuff;
}foo;

and the usage

foo Foo;
bar Bar = &Foo;

Without having the typedef in struct foo , you code won't compile.

Also, mind the ; after struct definition [and after int stuff also , though I assume that's more of a typo ].

This is how it should be:

typedef struct foo *bar;

struct foo {
    int stuff;
    char moreStuff;
};


int main()
{
  struct foo Foo;
  bar Bar = &Foo;

  return 0;
}

change the code like this.

typedef struct foo *bar;

struct foo {
  int stuff;
  char moreStuff;
};

struct foo Foo;
bar Bar = &Foo;

Or else you can use the typedef for that structure.

typedef struct foo {
  int stuff;
  char moreStuff;
}foo;

foo Foo;
bar Bar=&Foo;
this code is very obfuscated/ cluttered with unnecessary, undesirable elements.

In all cases, code should be written to be clear to the human reader.
this includes:
-- not making instances of objects by just changing the capitalization.
-- not renaming objects for no purpose

suggest:

struct foo 
{
    int stuff;
    char moreStuff;
};

struct foo   myFoo;
struct foo * pMyFoo = &myFoo;

which, amongst other things, actually 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