Dynamically allocate an array of unspecified size in C
You would probably want to use the same kind of techniques that std::vector uses. A simple implementation would be to make an array of some initial size, and whenever you run out of space, make a new array that's twice as large, copy the contents over to it, and use that as your new array.
In C, for a growable array of type T (might be char in your case -- I didn't make the code use templates because pure C doesn't have them) this might look something like:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct ArrayList
{
int capacity;
int size;
T* arr;
};
//initialCapacity must be a positive integer -- cannot be 0 in this implementation.
struct ArrayList* ArrayList_create(int initialCapacity)
{
struct ArrayList* newList = (struct ArrayList*) malloc(sizeof(struct ArrayList));
newList->capacity = initialCapacity;
newList->size = 0;
newList->arr = (T*) malloc(sizeof(T)*initialCapacity);
return newList;
}
void ArrayList_add (struct ArrayList* list, T elem)
{
if (list->size == list->capacity)
{
//double the capacity
list->capacity *= 2;
//make a new array with the new capacity
T* newArr = (T*) malloc(sizeof(T)*list->capacity);
//move the data over
memcpy (newArr, list->arr, sizeof(T)*list->size);
list->arr = newArr;
}
//now that sufficient capacity is ensured, add the new element
list->arr[list->size] = elem;
list->size++;
}
void ArrayList_print (struct ArrayList* list)
{
if (list->size == 0) { return; }
for (int i=0; i < list->size - 1; i++)
{
//printElement is a placeholder for printing an element of type T
printElement (list->arr[i]);
printf (", ");
}
printElement (list->arr[list->size - 1]);
}
//main method to test above code
int main()
{
struct ArrayList* list =ArrayList_create(1);
ArrayList_add(list, 2);
ArrayList_add(list, 5);
ArrayList_add(list, 7);
ArrayList_add(list, 1);
ArrayList_add(list, 11);
ArrayList_print(list);
return 0;
}
I tested a working version of this code for integers here: ideone .com/pOdIr2
Use techniques used to implement std::vector.
- Anonymous May 21, 2013