The difference between "struct foo *" and "foo *" where foo is a structure?

In C, is there a difference between writing "struct foo" instead of "foo" if foo is a structure?

For example:

struct sockaddr_in sin;
struct sockaddr *sa;

// Are these two lines equivalent?
sa = (struct sockaddr*)&sin;
sa = (sockaddr*)&sin;

Thanks / Erik

+5
source share
4 answers

In fact, standard “C” requires a keyword struct. This is optional in C ++.

This is why some people define such structures:

typedef struct foo { ... } bar;

to use barinstead struct foo. However, some C compilers do not apply this rule.

+10
source

Yes. In C (unlike C ++), structures are in their own namespace. Therefore, if you have identified

struct sockaddr { ... }

sockaddr s;
sockaddr *ps;

, typedef :

typedef struct sockaddr { ... } sockaddr;
sockaddr s, *p;
+6

You can only use "foo" if you typed it.

0
source

It depends on how the structure is defined. If defined using typedef, you don't need to put the stuct keyword in front.

typedef struct 
{
//
} aStruct;

aStruct abc;

but if its not typedef, you will need the struct keyword.

struct aStruct
{
//
} ;

struct aStruct abc;
0
source

All Articles