Below is our list example code.

list.h

#ifndef __LIST_H__
#define __LIST_H__

typedef struct {
    unsigned length;
    int *array;
} List;

// Construct, destruct
List *makeList();
void destroyList(List *);

// Add to end of list
void append(List *list, int val);
#endif 

list.c

#include <stdlib.h>
#include "list.h"

List *makeList() {
    // Space for a List
    List *ans = (List *) malloc(sizeof(List));

    // Initially an empty list
    ans->length = 0;
    ans->array = (int *) calloc(ans->length, sizeof(int));

    return ans;
}

void destroyList(List *list) {
    // Avoid use after free! Free array first.
    free(list->array);
    free(list);
}

void append(List *list, int val) {
    list->length += 1;
    list->array = (int *) realloc(list->array, list->length * sizeof(int));
    list->array[list->length - 1] = val;
}

useList.c

#include <stdio.h>
#include "list.h"

int main() {
    List *myList = makeList();

    printf("%p\n", myList);

    // Append some values
    append(myList, 42);
    append(myList, 175);
    
    // Print out the list
    for (int i = 0; i < myList->length; i+=1) {
        printf("%d\n", myList->array[i]);
    }

    puts(""); // To get a new line

    return 0;
}

Copyright © 2025 John Hott, portions Luther Tychonievich.
Released under the CC-BY-NC-SA 4.0 license.
Creative Commons License