resizing dynamic array c++

To resize a dynamic array in C++, you can follow these steps:

  1. Create a new array with the desired size.
  2. Copy the elements from the old array to the new array.
  3. Delete the old array.
  4. Update the pointer to the new array.

Here is an example of how you can implement these steps:

// Declare a pointer to an int to hold the address of the dynamic array
int* dynamicArray = new int[5];

// Populate the dynamic array with some values
for (int i = 0; i < 5; i++) {
    dynamicArray[i] = i;
}

// Resize the dynamic array to a new size of 10
int newSize = 10;
int* resizedArray = new int[newSize];

// Copy the elements from the old array to the new array
for (int i = 0; i < newSize; i++) {
    if (i < 5) {
        resizedArray[i] = dynamicArray[i];
    } else {
        // Initialize the remaining elements in the new array
        resizedArray[i] = 0;
    }
}

// Delete the old array
delete[] dynamicArray;

// Update the pointer to the new array
dynamicArray = resizedArray;

In this example, we start with a dynamic array of size 5. We then create a new dynamic array of size 10 and copy the elements from the old array to the new array. After that, we delete the old array and update the pointer to the new array. Now, the dynamic array has been successfully resized to the desired size.