Search code examples
cpointersdata-structuresstructtypedef

Problems with typedef struct name


Snippet 1:

typedef struct list_s {
    int key;
    struct list_s *next;
}list_t;

Snippet 2:

typedef struct list_s list_t;

struct list_s {
    int key;
    list_t *next;
};

I don't understand in snippet 1 or snippet 2 if the name of the struct is list_t or list_s. Usually I define a struct with name other_t as:

typedef struct{
    int n;
}other_t;

Also in snippet 1 and snippet 2, what does the referencing to the struct with a pointer, which it is inside of meant to do? I mean :

struct list_s *next;

What is it's function?


Solution

  • This is how one defines a struct type:

    struct Foo {
       ...
    };
    

    This can be used as follows:

    struct Foo foo;
    struct Foo *p;
    

    Using typedef, we can create an equivalent and compatible type without having to use struct everywhere.

    typedef struct {
       ...
    } Foo;
    

    This can be used as follows:

    Foo foo;
    Foo *p;
    

    When creating a self-referencing type (as snippets 1 and 2 do), you have to (directly or indirectly) use a struct type and not a "generic" type.

    struct Foo {
       struct Foo *next;
    };
    

    But nothing stops from also creating a "generic" type.

    typedef struct Foo Foo;
    

    (They can even have the same name, as is the case in my example.)

    Snippets 1 and 2 are equivalent, creating both a struct type (struct list_s) and an equivalent "generic" type (list_t).

    Snippet 3 creates only a "generic" type (other_t).


    The structure is probably used as the type for the nodes of a linked list. The pointer in one node would point to the next node in the list.

    list_t *head         list_t anon0         list_t anon1         list_t anon2
    +------------+       +------------+       +------------+       +------------+
    |         ---------->| key:  ...  |   +-->| key:  ...  |   +-->| key:  ...  |
    +------------+       +------------+   |   +------------+   |   +------------+
                         | next:   -------+   | next:   -------+   | next: NULL |
                         +------------+       +------------+       +------------+