Skip to content

Instantly share code, notes, and snippets.

@Jomy10
Created December 29, 2023 14:21
Show Gist options
  • Select an option

  • Save Jomy10/509e3914c00eff6b1e3b1f552354b13a to your computer and use it in GitHub Desktop.

Select an option

Save Jomy10/509e3914c00eff6b1e3b1f552354b13a to your computer and use it in GitHub Desktop.

Revisions

  1. Jomy10 created this gist Dec 29, 2023.
    46 changes: 46 additions & 0 deletions array.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    #include <stdio.h>
    #include <stdlib.h>

    #define Array(Type) struct array_##Type
    #define DefineArray(Type) struct array_##Type { Type* elements; int len; int cap; }
    #define array_get(array, index) (array).elements[index]
    #define array_set(array, value, index) (array).elements[index] = value
    #define create_Array(Type, cap) (struct array_##Type) { (Type*) malloc(cap * sizeof(Type)), 0, cap }
    #define destroy_Array(array) free((array).elements)
    #define array_append(array, value) (array).elements[(array).len++] = value
    #define array_append_checked(Type, array, value) array_reserve(Type, array); array_append(array, value)
    // Reserve minimum capacity
    #define array_reserve_capacity(Type, array, newCap) if ((array).cap < newCap) { \
    array_set_capacity(Type, array, newCap) \
    }
    // Set the capacity without checks
    #define array_set_capacity(Type, array, newCap) \
    array.cap = newCap; \
    array.elements = (Type*) realloc(array.elements, array.cap * sizeof(Type));
    // Allocate more when all elements in the array are full
    #define array_reserve(Type, array) if ((array).cap == (array).len) { \
    array_set_capacity(Type, array, (array).cap * 2) \
    }

    DefineArray(int);

    int main()
    {
    Array(int) a = create_Array(int, 1);
    array_append_checked(int, a, 1);
    array_append_checked(int, a, 2);
    array_append_checked(int, a, 4);
    printf("cap = %d\n", a.cap);
    array_reserve_capacity(int, a, 100);
    printf("cap = %d\n", a.cap);
    array_append(a, 10);

    for (int i = 0; i < a.len; i++) {
    int value = a.elements[i];
    printf("%d\n", value);
    }
    array_set(a, 5, 1);
    printf("%d\n", array_get(a, 1));

    return 0;
    }