Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Vector/ArrayList/LinkedList

Tags:

c

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.

like image 371
SBSTP Avatar asked Nov 30 '22 09:11

SBSTP


2 Answers

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. ;)

like image 146
BlackBear Avatar answered Dec 15 '22 16:12

BlackBear


Use an existing implementation. There are billions. Glib is probably a good place to start, or LibH.

like image 44
Conrad Meyer Avatar answered Dec 15 '22 14:12

Conrad Meyer