0

When writing this C struct:

typedef struct node_s* node_t;

struct node_s {
  int value;
  node_t next;
};

Anytime we define a variable of type node_t we don't need to add a pointer * ?

For example:

node_t f(node_t node) {
...
}

such that f receives a node and returns one.

Obsidian
  • 3,719
  • 8
  • 17
  • 30
Kim
  • 77
  • 7
  • With your type-alias, the type `node_t` is an alias for `struct node_s *`. So if you want `f` to accept a `struct node_s *` argument, and return a `struct node_s *`, then you have declared `f` correctly. – Some programmer dude Jun 04 '23 at 16:00
  • 7
    With that said, it's often recommended *against* creating type-aliases for pointers. One reason is that it's too common to forget that it's a pointer, and use the alias `node_t` instead of `struct node_s` (for your specific example). As an example `malloc(sizeof(node_t))` instead of `malloc(sizeof(struct node_s))`. – Some programmer dude Jun 04 '23 at 16:02
  • 5
    See [Is it a good idea to typedef pointers?](https://stackoverflow.com/q/750178/15168) TL;DR — no, except perhaps for pointers to functions. Roughly, "don't do it" — `typedef struct node_s *node_t;` is a bad idea, even if you use a bit of Hungarian notation and use `typedef struct node_s *pnode_t;`. It might conceivably be OK if it is an opaque type — but you use `FILE *` quite happily. Given `typedef struct node_s node_t;`, you could use `node_t *` everywhere outside the implementation of the library code that actually manipulates `node_t` variables. – Jonathan Leffler Jun 04 '23 at 16:25

1 Answers1

1

node_t is an alias for struct node_s *, so

node_t p;

is exactly equivalent to

struct node_s *p;

and

node_t f( node_t node )

is exactly equivalent to

struct node_s *f( struct node_s *node )

Having said all that...

It's generally not a good idea to hide a pointer behind a typedef unless you also provide an API that hides the "pointer-ness" of the type from the user.

If the user of your type has to explicitly dereference it or access a member in order to use it properly, then don't hide the pointer-ness or the struct-ness behind a typedef.

John Bode
  • 119,563
  • 19
  • 122
  • 198