Menu
Coddy logo textTech

Dynamic Array - Insertion

Lesson 14 of 14 in Coddy's C++ Pointers course.

Finally, it's important to know how we can dynamically add an element to an array. If you're not able to use a vector, and your array is already full, you need to find a way to dynamically modify the length of the array and add the wanted element

This is a small example of how we can dynamically change the array and make it work as if it were a vector

  • We have the initial dynamically allocated array
  • We create a new dynamically allocated array with a length of + 1
  • We copy all of the elements from the old to the new array
  • At the last index (the +1) we add the wanted element
  • We delete the old array
  • And we make the pointer of the old deleted array to point to the new modified array
  • Finally, at the end of the program, we delete the pointer of the array for one last time
int *array = new int[5]; // Initial array
for(int i = 0; i < 5; i++)
    array[i] = i + 1;
    
int *newarray = new int[6]; // New array with +1 length

for(int i = 0; i < 5; i++)
    newarray[i] = array[i]; // Copy all of the elements
newarray[5] = 6; // Add the last element

delete[] array; // Deallocate the old array
array = newarray; // Set it to point to the new

for(int i = 0; i < 5; i++)
    cout << array[i] << " ";
    
delete[] array; // Deallocate the new
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Given the dynamically allocated array, don't change the default code, in the middle add code to input 3 numbers to add to the back of the array like the example in the lesson

Do NOT change the default code

Try it yourself

#include <iostream>

using namespace std;

int main() {

    int *numbers = new int[5];
    for(int i = 0; i < 5; i++)
        numbers[i] = i + 1;
    // DON'T CHANGE THE CODE ABOVE


    // Enter your code here

    // Input 3 integers

    // Dynamically add them to the array "numbers"


    // DON'T CHANGE THE CODE BELOW
    for(int i = 0; i < 8; i++)
        cout << numbers[i] << " ";
    delete[] numbers;

    return 0;
}

All lessons in C++ Pointers