I have implemented a generic dynamic array implementation using defines. As I am new to C, I am not sure whether the code has any flaws. The code is as follows,
#define INIT_CAPAC 5 #define INC_CAPAC 5 #define list(t) struct{ t* data; unsigned int count; unsigned int capac;} #define list_init(lst) lst.data = malloc(sizeof(*lst.data) * INIT_CAPAC); \ lst.count = 0; \ lst.capac = INIT_CAPAC; #define list_append(lst, item) lst.data[lst.count++] = item; \ if(lst.count >= lst.capac) { \ realloc(lst.data, sizeof(*lst.data) * (lst.capac + INC_CAPAC)); \ } #define list_count(lst) lst.count #define list_at(lst, index) lst.data[index] typedef list(int) int_list_t; int main() { int_list_t arr; list_init(arr); list_append(arr, 10); list_append(arr, 20); list_append(arr, 30); printf("Count: %d\n", list_count(arr)); printf("Item at 0: %d\n", list_at(arr, 0)); printf("Item at 1: %d\n", list_at(arr, 1)); printf("Item at 2: %d\n", list_at(arr, 2)); }
This implementation seems better than other C solutions because,
We don't store the item size as the part of array structure. In other dynamic array implementations, the size of each element is stored in along with the element count and array capacity.
This is as intuitive as the dynamic arrays in other high level languages like C++, C#.