While working on my C programming skills I wrote a small program to simulate the functionality of dynamic arrays on other languages. That is arrays that grow as you add elements to them instead of having a fixed size. I decided that is has to be reusable and that you should be able to have multiple instances of them, so I structured my code with that in mind.
So this is the file structure:
I’m going to hold the data for each array in a struct:
|
1 2 3 4 5 |
struct ArrayData { int *pointer; int counter; int size; }; |
With this we will keep track of the current number of elements on the array (counter), the current size of memory allocated (size), and a pointer to the array.
Next we want to define some basic operations:
|
1 2 3 |
struct ArrayData *initArray(); int addElement(struct ArrayData *array, int number); int getElement(struct ArrayData *array, int index); |
Initializing the array:
|
1 2 3 4 5 6 7 |
struct ArrayData *initArray() { struct ArrayData *newArray = malloc(sizeof(struct ArrayData)); newArray->pointer = calloc(1000, sizeof(int)); newArray->size = 1000; newArray->counter = 0; return newArray; } |
We first allocate memory for our struct, then allocate memory for our array, in this case for 1000 elements of type int. Remember that the -> notation is equal to (*newArray).pointer, since newArray is a pointer itself we need to dereference it first to get access to the structure members.
Now that we can initialize our array we will want to be able to add elements to it:
|
1 2 3 4 5 6 7 8 9 10 |
int addElement(struct ArrayData *array, int number) { if (array->counter >= array->;size) { resizeArray(array); } *(array->pointer + array->counter * sizeof(int)) = number; array->counter += 1; return 0; } |
Checking that our current number of elements is smaller than the size of the array is probably a good idea, if that is not the case we will make our array bigger, after that we use the start address of our array and add to it the current number of elements on the array, this would the be equivalent of using a subindex in a normal array (e.g. array[10])
Getting an element from the array is pretty simple as well:
|
1 2 3 4 5 6 7 8 |
int getElement(struct ArrayData *array, int index) { if (array->counter >= array->size) { return -1; } int *data = array->pointer + index * sizeof(int); return *data; } |
In the next post we will test this and fix an interesting bug.