The use of a pointer to an unnamed struct in C?

2019-04-15 06:43发布

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 ?

3条回答
Evening l夕情丶
2楼-- · 2019-04-15 07:05

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));
查看更多
The star\"
3楼-- · 2019-04-15 07:14

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.

查看更多
【Aperson】
4楼-- · 2019-04-15 07:21

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;
  };
查看更多
登录 后发表回答