Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "struct foo*" and "foo*" where foo is a struct?

Tags:

c

struct

typedef

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

For example:

struct sockaddr_in sin;
struct sockaddr *sa;

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

Thanks /Erik

like image 702
Erik Öjebo Avatar asked Jan 09 '09 12:01

Erik Öjebo


2 Answers

In fact, in standard "C" it's required to specify struct keyword. This is optional in C++.

This is the reason some people define structs like this:

typedef struct foo { ... } bar;

to be able to use bar instead of struct foo. However, some C compilers do not enforce this rule.

like image 81
mmx Avatar answered Nov 24 '22 02:11

mmx


Yes. In C (as opposed to C++), structs are in their own namespace. So if you defined a

struct sockaddr { ... }

you may not use it as

sockaddr s;
sockaddr *ps;

In order to make that legal, you may use typedef in order to import into the non-struct namespace of type names:

typedef struct sockaddr { ... } sockaddr;
sockaddr s, *p;
like image 44
Avi Avatar answered Nov 24 '22 01:11

Avi