-1

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?

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • the name of the struct is always `struct list_s`. In the last version, the struct has no name. – user253751 Feb 02 '23 at 18:49
  • If you have a self-referential structure (if it contains one or more pointers to its own type), it must have a tag (e.g. `struct list_s`). Lists are quintessential self-referential structures. If your structure is not self-referential, the tag is optional. If you don't have a tag, you must refer to the type name given by the `typedef`. Note that the Linux kernel avoids typedefs for structure types, insisting that you always use `struct tag`. – Jonathan Leffler Feb 02 '23 at 19:01

1 Answers1

2

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 |
                     +------------+       +------------+       +------------+
ikegami
  • 367,544
  • 15
  • 269
  • 518