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.
#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
- Hello, World · The classic first C program.
- Sum of two numbers · Read two numbers with scanf and print their sum.
- Check a prime number · Test whether a number is prime by trying divisors up to its square root.
- Pointers: swap two numbers · Pass addresses to a function so it can change the caller’s variables.
- Sort an array (bubble sort) · Sort numbers by swapping neighbours until nothing moves.