Help more people learn by sharing this post!

Dynamic Arrays in C – part 1

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:

  • main.c – initialize the array and fill it for testing purposes
  • array.h – function declarations
  • array.c – function definitons


I’m going to hold the data for each array in a struct:

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:

Initializing the array:

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:

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:

In the next post we will test this and fix an interesting bug.