Programs & Examples
Structures, Unions, Enums · Study material
Singly linked list with a self-referential structure
A node holds a value and a pointer to the next node of the same type. Insert at the front, print, and free every node.
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node *next; /* a pointer to the same struct type */
};
struct node *push_front(struct node *head, int v) {
struct node *n = malloc(sizeof *n);
if (n == NULL)
return head;
n->value = v;
n->next = head;
return n;
}
int main(void) {
struct node *head = NULL;
for (int v = 3; v >= 1; v--)
head = push_front(head, v);
for (struct node *p = head; p != NULL; p = p->next)
printf("%d -> ", p->value);
printf("NULL\n");
while (head != NULL) { /* free every node */
struct node *next = head->next;
free(head);
head = next;
}
return 0;
}
1 -> 2 -> 3 -> NULL
Complex numbers with structures
Functions can take and return structs by value; a compound literal builds the result in one expression.
#include <stdio.h>
struct complex {
double re, im;
};
struct complex add(struct complex a, struct complex b) {
return (struct complex){a.re + b.re, a.im + b.im}; /* compound literal */
}
struct complex mul(struct complex a, struct complex b) {
return (struct complex){a.re * b.re - a.im * b.im, a.re * b.im + a.im * b.re};
}
int main(void) {
struct complex x = {1, 2}, y = {3, -1};
struct complex s = add(x, y), p = mul(x, y);
printf("sum = %.1f%+.1fi\nproduct = %.1f%+.1fi\n", s.re, s.im, p.re, p.im);
return 0;
}
sum = 4.0+1.0i product = 5.0+5.0i
A fixed-size stack in a structure
The array and its top index travel together, and the functions report "full" or "empty" instead of overflowing.
#include <stdbool.h>
#include <stdio.h>
#define CAP 4
struct stack {
int items[CAP];
int top;
};
bool push(struct stack *s, int v) {
if (s->top == CAP)
return false;
s->items[s->top++] = v;
return true;
}
bool pop(struct stack *s, int *v) {
if (s->top == 0)
return false;
*v = s->items[--s->top];
return true;
}
int main(void) {
struct stack s = {.top = 0};
for (int v = 1; v <= 5; v++)
if (!push(&s, v))
printf("push %d failed: stack full\n", v);
int v;
while (pop(&s, &v))
printf("%d ", v);
printf("\n");
if (!pop(&s, &v))
printf("pop failed: stack empty\n");
return 0;
}
push 5 failed: stack full 4 3 2 1 pop failed: stack empty