Dynamic Array - Data
Before we can write any functionality we need to get the data structure in place. We have the plan, so we can capture this in a comment. The following is the comment I added as a prompt to get copilot to help me out.
The @tparam
indicates that you will have a type parameter named T
. Headerdoc doesn’t actually contain tags for fields, but we can still use these to indicate the elements that we need in the struct.
Once you add this in, wait for the suggestion and check to make sure that it looks right.
We can add a main
at the bottom of the code, and put in a comment that you want to create a dynamic array of int. Copilot should then declare this for you.
Make sure this compiles before you move on.
Creating a new dynamic array
Next we need to have some code that will create new dynamic arrays for us. This can allocate space on the heap, and make sure that the fields are all setup correctly.
Try something like this as the prompt for this function.
Copilot will probably generate something close to what you need, but it will probably need some help. For me, it didn’t think about the case that the malloc
failed to allocate memory. So I added a comment // Make sure that data was allocated, if not set capacity to 0
to ensure it had an if statement when assigning the capacity.
Before updating main
, we should add a delete_dynamic_array
procedure. We have the memory allocations in mind, so now we can add the code to remove this allocation.
Try the following prompt:
Copilot was a bit lazy for me here. I had to add in a few extra prompts to get what I wanted. The main one was getting it to set size
and capacity
to 0. While this is not essential, it makes sure that any dangling pointers won’t accidentally see the old data as we just left it there when the array was deleted.
Once this is in place, you can now update main to initialise and free the dynamic array. The following code includes the updated prompts which can help Copilot build this for you.
When you update the comment about initialising the array, you can remove the ;
from the related line and code and wait a second. It should then give you suggestions on how to make that change. If not, you can call the new_dynamic_array<int>
function yourself.
Compile and run the program. While there is no output, at least you will know that it was able to create and free the space on the heap.
Once this is working you can move on to adding the resizing the data in the array.