How to make an array with a dynamic size? General usage of dynamic arrays (maybe pointers too)?

For C++:

If you just need a container just use std:vector. It will take care all the memory allocations necessary for you. However if you want to develop your own dynamic container (whatever reasons you have) you have to take care off the memory allocations yourself. That is, when your array grows you have to allocate new memory chunk, copy present array values to the new memory location and add new values to the newly allocated memory. Usually one wraps this kind of logic inside a separate class e.g. GrowingArray(like standard provided vector class)

EDIT

To elaborate more on my answer (given that you are using this for learning purpose):

store it in an array without a starting size (i.e. not -> array[5];)

Here you want to use something like this: int * myDynamicArray; When a user inputs some values you allocate memory chunk where those values are going to be stored: myDynamicArray = new int[5]; with the size of your initial input. I would as well recommend to save the size of the array in some variable: int arraySize = 5; If later on you want to append new values to your myDynamicArray first of all you have to allocate new memory chunk for grown array (current array elements + new array elements). Lets say you have 10 new values coming. Then you would do: int* grownArray = new int[arraySize+10]; this allocates new memory chunk for grown array. Then you want to copy items from old memory chunk to the new memory chunk and add user appended values (I take it you are using this for learning purposes thus I provided you simple for cycle for copying elemts. You could use std:copy or c like memcopy as well):

int i = 0;
for (; i < arraySize; ++i)
   {
   grownArray[i] = myDynamicArray [i];
   }
// enlarge newly allocated array:
arraySize+= 10;
for (; i < arraySize; ++i)
   {
   grownArray[i] = newValues from somewhere
   }
// release old memory
delete[] myDynamicArray;
// reassign myDynamicArray pointer to point to expanded array
myDynamicArray = gronwArray;

Leave a Comment