Dynamic Array - Add and Resize
The add and resize functions will be central to this, and will have the main thinking around dynamic memory management. This will allow you to add new elements to a dynamic array, and to keep adding them even when you exceed the array’s initial capacity.
Resize
Add is going to need resize, so we are best to implement the resize code first. The following prompt should help Copilot get you something close to what we want.
For me, it kept wanting to do silly things like use malloc
instead of realloc
and then manually be copying over the data one element at a time. This is slow, inefficient, and unnecessary. I ended up accepting the malloc
suggestion, then I deleted the malloc
code and the code to copy the array over and added a new comment at the right location to prompt it to use realloc
. Similarly, I had to prompt it to update the capacity if the new capacity was smaller. The prompts are below.
Add
To put values in the array, the user (a programmer) will have to call the add
method. This will insert the value at the end of the currently used part of the array, and increase the array’s size. If there is no capacity to do this, the array will first have to try to resize the array, if that succeeds then it can add as normal.
Here is a starting prompt:
For me this kept trying to put the resize code in add, rather than calling the resize itself. Here are some of the extra comments that I added.
Test in main
To test this in main I used the following comment as a prompt.
At this point, main
is looking like this for me.
Make sure your program builds and runs before you move on.
Try working with an initial capacity of 0
. I ended up changing my add
method to double and + 1
so that it works when the capacity was originally 0. As 2 * 0 is still 0.