RUN

Structs and malloc in C

Build a small linked list on the heap, print it and free it. Press Run to try it, then change the code and run it again.

main.c

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int value;
    struct Node *next;
};

int main(void) {
    struct Node *head = NULL;
    for (int i = 3; i >= 1; i--) {
        struct Node *node = malloc(sizeof *node);
        node->value = i * 10;
        node->next = head;
        head = node;
    }

    for (struct Node *p = head; p != NULL; p = p->next) printf("%d -> ", p->value);
    printf("NULL\n");

    while (head) {
        struct Node *next = head->next;
        free(head);
        head = next;
    }
    return 0;
}
Output

Press Run to see the output.

More C examples

Open the full C online compiler →