CC

C: Data structures – code examples

Contents

Array: sum and maximum

Data structures#array#list#sizeofCompare in all languages
Use case: Process series of measurements, e.g. determine the sum, average or maximum.
#include <stdio.h>

int main(void) {
    int zahlen[] = {5, 3, 8, 1};
    size_t n = sizeof(zahlen) / sizeof(zahlen[0]);
    int summe = 0, max = zahlen[0];
    for (size_t i = 0; i < n; i++) {
        summe += zahlen[i];
        if (zahlen[i] > max) max = zahlen[i];
    }
    printf("n=%zu sum=%d max=%d\n", n, summe, max);
    return 0;
}

C arrays have a fixed size; you compute the number of elements with sizeof. For growing lists you need malloc/realloc (see the snippet "Dynamic array").

Key-value table (linear search)

Data structures#map#dictionary#struct#strcmpCompare in all languages
Use case: Resolve small mappings such as configuration names or command names.
#include <stdio.h>
#include <string.h>

struct Eintrag { const char *key; int wert; };

int main(void) {
    struct Eintrag map[] = {{"red", 1}, {"green", 2}, {"blue", 3}};
    const char *gesucht = "green";
    for (size_t i = 0; i < sizeof map / sizeof map[0]; i++) {
        if (strcmp(map[i].key, gesucht) == 0) {
            printf("%s -> %d\n", gesucht, map[i].wert);
        }
    }
    return 0;
}

C has no built-in map. For a few entries, an array of structs with linear search is enough; for many, you build a hash table or use a library (e.g. uthash).

struct with functions (instead of a class)

Data structures#struct#oop#typedefCompare in all languages
Use case: Bundle data and related operations, e.g. users, products or configurations.
#include <stdio.h>

typedef struct { char name[20]; int alter; } Person;

void geburtstag(Person *p) { p->alter++; }

int main(void) {
    Person ada = {"Ada", 36};
    geburtstag(&ada);
    printf("%s is %d\n", ada.name, ada.alter);
    return 0;
}

C has no classes: you use a struct for the data and functions that receive a pointer to it as their first parameter (p->alter). This replaces self/this; there is no inheritance.

Sorting structs with qsort

Data structures#qsort#sorting#function pointer
Use case: Order records by a field, e.g. users by age or products by price.
#include <stdio.h>
#include <stdlib.h>

typedef struct { const char *name; int alter; } Person;

int nach_alter(const void *a, const void *b) {
    const Person *x = a, *y = b;
    return (x->alter > y->alter) - (x->alter < y->alter);
}

int main(void) {
    Person p[] = {{"Ada", 36}, {"Bob", 25}, {"Cy", 41}};
    qsort(p, 3, sizeof p[0], nach_alter);
    for (int i = 0; i < 3; i++) printf("%s (%d)\n", p[i].name, p[i].alter);
    return 0;
}

qsort sorts arbitrary arrays via a comparison function (function pointer). The void * values are cast to the real type. Return value: negative, 0 or positive.

Linked list

Data structures#list#malloc#pointer#node
Use case: Insert and remove data dynamically when order matters (queues, history lists).
#include <stdio.h>
#include <stdlib.h>

typedef struct Node { int wert; struct Node *next; } Node;

Node *push_front(Node *kopf, int wert) {
    Node *n = malloc(sizeof *n);
    if (n == NULL) exit(EXIT_FAILURE);
    n->wert = wert;
    n->next = kopf;
    return n;
}

int main(void) {
    Node *liste = NULL;
    for (int i = 1; i <= 3; i++) liste = push_front(liste, i);
    for (Node *n = liste; n != NULL; n = n->next) printf("%d ", n->wert);
    printf("\n");
    while (liste != NULL) {
        Node *weiter = liste->next;
        free(liste);
        liste = weiter;
    }
    return 0;
}

Each node points to the next one. When freeing, next is saved before free. Output: 3 2 1, because insertion happens at the front.