I'm doing a little program in C and I'd need a kind of vector/ArrayList/LinkedList but I'm working with C. Any idea on how I could do that kind of thing in C?
I want to store structs and then append/remove some.
For resizable arrays you can use malloc()
and realloc()
. These allow you to reserve (with malloc()
) and resize (with realloc()
) a certain amount of space on the heap. They're used this way:
int* a = malloc(10 * sizeof(int));
if(a == NULL) {} // malloc() was unable to allocate the memory, handle the
// error and DO NOT use this pointer anymore
// now you can treat a as a normal array of 10 ints:
a[4] = 51;
// suppose 10 ints aren't no more enough:
a = realloc(a, 20 * sizeof(int));
if(a == NULL) {} // same thing as before
// here you have 20 ints, the previous 10 are still there
a[18] = a[4]
// don't forget to free the memory when you have finished:
free(a);
Just replace 'int' with your struct type. ;)
Use an existing implementation. There are billions. Glib is probably a good place to start, or LibH.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With