Link Search Menu Expand Document

Below is our list example code.

list.h

#ifndef __LIST_H__
#define __LIST_H__

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

List *makeList();
void destroyList(List *);

void append(List *list, int val);
#endif 

list.c

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

List *makeList() {
    List *ret = malloc(sizeof(List));

    ret->length = 0;
    ret->array = (int *) calloc(ret->length, sizeof(int));

    return ret;
}

void destroyList(List *l) {
    free(l->array);
    free(l);
}

void append(List *list, int val) {
    list->length += 1;
    list->array = 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();

    append(myList, 42);
    append(myList, 175);

    for (int i = 0; i < myList->length; i+=1) {
        printf("%d\n", myList->array[i]);
    }
    printf("%p\n", myList);

    return 0;
}

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