3
typedef struct llist {
    int valor;
    struct lligada *prox;
} *LInt;

So this is how linked lists are implemented in C at my university and I have been wondering why in the last line they put a pointer to LInt instead of just LInt.

typedef struct lligada {
    int valor;
    struct lligada *prox;
} LInt;

Wouldn't this be simpler? I mean it's this last example that I see in tutorials around the web and if we want a pointer to the struct we would just write something like

LInt *foo = ...;

What confuses me is that they declare the pointer in the struct and in the exercises they still do the declaration above. Is there any special reason for this? Is this normal? They also do this for binary trees.

rybur
  • 51
  • 5

1 Answers1

1
typedef struct llist {
    int valor;
    struct lligada *prox;
} *LInt;

makes LInt equivalent to struct llist* (with the star included). This practice of typedefing pointers is pretty much discouraged in all modern resources on C I've come across but it has been used historically, notably the lcc compiler uses this practice a lot (their convention capitalizes the pointer typedefed name as well).

The problem with typedefing pointers is that it's potentially confusing and you can suddenly pass 0 (as NULL) with a special value through them, however if you have a naming convention (such as capitalizing each pointer typedef) then the star is effectively not hidden but just expressed as an upper case letter, although it might still be confusing to someone foreign to your codebase.

So to summarize, with

typedef struct llist {
    int valor;
    struct lligada *prox;
} *LInt;

you'd then use it like so:

LInt foo = NULL; 

whereas without the star in the typedef, the above would be:

LInt *foo = NULL; 
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • Not complaining about your answer, yet it is surprising to see a post-able answer after _marked as duplicate_. – chux - Reinstate Monica May 23 '18 at 23:32
  • @chux I was surprised to be able to post it as well. Must have been a race condition. – Petr Skocik May 23 '18 at 23:35
  • I understand your answer but the thing is even with the struct defined with the typedef and the start they still do the declarations with the star, is there any reason for that? isn't that using a double pointer? – rybur May 23 '18 at 23:36
  • @rybur Yes. If they add another star the variable will be a doubly-indirect pointer. – Petr Skocik May 23 '18 at 23:37
  • and is that useful in anyway? or bad? – rybur May 23 '18 at 23:40
  • @rybur I'd say it's mostly bad. At worst it'll confuse someone, at best it'll save you from having to type an `*`. The scales seem to be tipped against it. – Petr Skocik May 23 '18 at 23:45