Possible Duplicate:
Purpose of struct, typedef struct, in C++
typedef struct vs struct definitions
I am aware that there are two ways of declaring structs in C
struct point{
int x, y;
};
and:
typedef struct{
int x, y;
} point;
but what is the difference between these two methods and when would I use the typedef method and not the other ?
There is only one way to declare a
structin C, using thestructkeyword, optionally followed by the name of the structure, then followed by the member fields list in braces. So you could have:Here
point_stis the name (or tag) of your structure. Notice that structure names have a different namespace in C than types (this is different in C++). So I have the habit of suffixing structure names with_stas shown above.You can (independently) define a type name using typedef, e.g.
(you can use
typedefon any C type, BTW).For exemple Gtk and Glib has a lot of opaque types which are such opaque structures; only the implementation knows and cares about the structure members.
Of course the compiler needs to know the field of a structure to allocate it; but if you only use pointers to an opaque structure, you don’t need to declare the structure (i.e. its fields in braces).