2

I have learned that typedef allows me to give a struct a name that can be referenced without needing to specify struct before the name. For example, I can create an instance of Network 2 different ways struct Network network; or like Network network;

typedef struct Network {
  bool enabled;
  long long counter;
} Network;

However, if I needed to create a pointer to my Network struct from inside of the struct, I would need to use the non-typedef name like the following.

typedef struct Network {
  bool enabled;
  long long counter;
  struct Network* network;
} Network;

All of that being said I ran into 1 case which I can't figure out or find any resources on which you can see in the following example. Now what does this actually do? What does this pointer version of Network do and what are the uses versus the other 2 examples I provided above?

typedef struct Network {
  bool enabled;
  long long counter;
} Network, *PNetwork;

I initially thought this was the same as just assigning Network as a pointer, but I am not sure. For example, I initially thought the following would be the same, but I am not sure.

Network* network;
PNetwork network2;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • It means that `PNetwork` is an alias for `struct Network *`, i.e. a pointer to the structure. – Barmar Mar 31 '23 at 23:17
  • `typedef` is not just for structures. It allows you to define an alias for *any* type expression. This is how you define an alias for a pointer type. – Barmar Mar 31 '23 at 23:18
  • 1
    Pointer typedefs are generally considered an anti-pattern, see https://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers – Barmar Mar 31 '23 at 23:19
  • @Barmar What do you mean by an alias to a pointer type? Are the two lines of code at the bottom of my question (both pointers to Network) the same? – IgnoreExeption Mar 31 '23 at 23:21
  • Yes, they're equivalent. – Barmar Mar 31 '23 at 23:22

1 Answers1

2

There are declared two typedef names

typedef struct Network {
  bool enabled;
  long long counter;
} Network, *PNetwork;

the alias (typedef name) Network for the type struct Network and the alias PNetwork for the pointer type struct Network *.

You could consider such a typedef declaration by analogy with variable declarations as for example

int Network, *PNetwork;

Only in typedef declarations there are declared type names instead of variables.

typedef int Network, *PNetwork;

So using these typedef names you could declare variables like for example

Network my_integer = 10;
PNetwork pointer_to_my_integer = &my_integer;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335