Home > Mobile >  What does this code snippet do? ('struct foo{struct foo *var;};')
What does this code snippet do? ('struct foo{struct foo *var;};')

Time:11-01

everyone! I've came across some snippet of code while searching for garbage collecting in C. and I read this website's title which is: "Writing a Simple Garbage Collector in C". here's the website: https://maplant.com/gc.html

And this Struct is eye-catching: (for me)

typedef struct header {
    unsigned int    size;
    struct header   *next;
} header_t;

From what I know, the typedef struct header is used to save some keystrokes so if using the struct, you'll just type

header_t hdr;

instead of:

struct header hdr;

What I do not know is: (what does this do)

Line 3, Starting from Col. 0.

struct header    *next;

Please enlighten me, thank you! <3 Oh and I've found something in this site that has the exact question but I'm not satisfied with its answer.

CodePudding user response:

The struct is a node in a linked list.

The pointer element in the struct can point to another instance of the struct. This allows you to dynamically allocate memory for an instance of the struct and put it at the end (or the beginning) of the list. You'll have a pointer to the first element, commonly referred to as the head of the list. Then you can traverse the list by following the next pointers until you find one set to NULL which indicates the end of the list.

  • Related