What's the use for something like
typedef struct
{
int field_1;
float field_2;
}*T;
in C
?
Since a struct
is a datatype in C
, where the information about the datatype pointed by T
is stored and how to correctly initialize a variable var
that is declared as T var
?
T
is an alias for a pointer to the structure. The structure itself is not a type, but T
is.
T
is not stored anywhere but in the compilers internal tables for types.
You can use it like
T myVariable = malloc(sizeof(*myVariable));
I would expect something like that (pointer-to-unnamed-struct) to be used in order to describe the data which are coming from outside of the program in question (e.g. given as a return value from a library function, when it is allocated and deallocated by that library). Then such typedef is just a specification how to access these data.
The use is as if the struct was named. I.e. you can access struct fields via this pointer. For example:
void fun(T p) {
if (p->field_1 == 0) p->field_2 = 1.2345;
}
If you never need to reference a structure itself by a name, there is no need to give it one. The info about structure (and its members) is stored in compiler tables in the same way as for named structures.
This construct is useful in defining complex data structures (possibly with unions) and not to pollute global name space with useless names. For example:
struct myUsefulStructure {
int stype;
union {
struct { // a structure which is never referenced itself
...
} x;
struct { // another structure which is never referenced itself
...
} y;
} u;
};