Created
December 29, 2023 14:21
-
-
Save Jomy10/509e3914c00eff6b1e3b1f552354b13a to your computer and use it in GitHub Desktop.
C Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment