day
day

Reputation: 301

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?

Upvotes: 1

Views: 239

Answers (4)

user3629249
user3629249

Reputation: 16540

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

Upvotes: 0

Arjun Mathew Dan
Arjun Mathew Dan

Reputation: 5298

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;
}

Upvotes: 1

Karthikeyan.R.S
Karthikeyan.R.S

Reputation: 4041

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;

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134326

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].

Upvotes: 2

Related Questions