I am just wondering whether it is possible for me to add/append elements to a list in C, and I would go around doing it?
e.g.
int numbers[6] = {5,3,5,1,3,6}
Let's say I wanted to add another number to the array 'numbers', how would I do that?
I am just wondering whether it is possible for me to add/append elements to a list in C, and I would go around doing it?
e.g.
int numbers[6] = {5,3,5,1,3,6}
Let's say I wanted to add another number to the array 'numbers', how would I do that?
Well, the original array needs to be malloc
'ed, rather than on the stack. Then you can use realloc
:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int * numbers = malloc(6*sizeof(int));
for(int ii = 0; ii < 6; ++ii) {
numbers[ii] = 5;
}
numbers = realloc(numbers, 7*sizeof(*numbers));
if(!numbers) {
printf("Memory allocation failed, sorry dude!\n");
exit(1);
}
numbers[6] = 7;
for(int ii = 0; ii< 7; ++ii) {
printf("%d\n", numbers[ii]);
}
free(numbers);
}
You would need to use realloc
.
void *new_array = realloc(old_array, new_array_size);
if (!new_array_size) {
// check for error with realloc
}
old_array = new_array;
This is a very basic implementation of std::vector
. For more info on realloc
see here.
This answer is for the more general case of expanding an array in C. It assumes that you have used malloc, calloc, etc.
to generate your array. If not realloc
will give undefined behavior since the memory has not been allocated.
The simplest solution probably would be to make an array that is larger than it needs to be upon declaration.
Your example array has six elements, so perhaps the array would be declared to have a length of eight. This would be enough to allow two more elements to be "added". You would have to keep track of both what the actual length of the array is and the number of relevant elements it contains are (eight and six respectively).
If you wanted to "add" a third element then you would have to make a new array. The new array could be twice the length of the previous one (sixteen). Copy all the elements of the previous array to the new one and then "add" the new element.
The array is of fixed size and can only be extended via realloc or malloc/memcpy as others have already said. There are various schemes for making this more efficient which usually require making the array opaque and operated on by a set of functions.
If you only need a list then the FreeBSD queue primitives are probably a good place to start, they provide single and doubly linked lists. Code is a single header file. If anything it shows how to implement a robust list/queue primitive.
There are various libraries for collection management such as GTK/Glib but that comes with a whole slew of other concerns you may or may not need.
The ultimate in high level functional C is probably libCello if you don't mind pushing the language to its limits.