Home > database >  Does it make sense to have both name and a pointer to a structure?
Does it make sense to have both name and a pointer to a structure?

Time:10-16

typedef struct net_path_s
{
    uint8    path_len;                     /* network path length */
    uint8    net_path[2 * MAX_ROUTE_LEN];  /* network path */
} net_path_t, *net_path_pt;

The pointer is meant for the structure. Does it make sense to have both name and a pointer? And why are they using it?

CodePudding user response:

Because this declaration is a typedef it defines types, not variables. net_path_t is another name for this structure type, and net_path_pt is another name for a pointer to this structure type. You don't need to have both.

For some reason, some people prefer to write net_path_pt instead of net_path_t*. Defining pointer typedefs seems to be common in older APIs.

CodePudding user response:

Those are 2 things (or perhaps even 3) done at once. They can be decomposed into first:

struct net_path_s
{
    uint8    path_len;                     /* network path length */
    uint8    net_path[2 * MAX_ROUTE_LEN];  /* network path */
};

that defines a struct.

And second:

typedef net_path_s net_path_t, *net_path_pt;

that creates two typedefs. One is net_path_t which is an alias of net_path_s and the other is net_path_pt which is an alias of net_path_s*.

The latter is conceptually "creation of pointer type".

C syntax is "a pointer to type X". There is char and char* is a pointer to it. char* looks like a mere variant of char, as in char a, *b, c;.

Humans usually find it easier to think in "a type of pointer to X" way. So that's the rationale for typedef char* as eg. pstr. Now pstr looks like a type of its own. So you write char a, c; pstr b;.

  • Related