Menu
Coddy logo textTech

Dynamic Array

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

Thanks to modern programming, and high-level programming languages we have data structures, and algorithms that do complex work for us simply. We have the vector, stack, queue, etc.

Specifically, the vector in C++ is a data structure representing a dynamic array. You don't need to initialize its length, when we use the .push_back() method its length automatically changes, and the elements we want to add get automatically added, and so on. 

But behind the scenes, the vector gets dynamically changed, and all of the methods, and functions are prebuilt by someone else. But, it's good to know how dynamically allocating an array works.

For example, let's say we have an array, we can declare it and initialize its length by using new and reserving space in the memory. We can later on fill in those locations in the memory with values we want.

// Allocating for 5 integers:
int *array = new int[5];
    
// Filling up the array:
for(int i = 0; i < 5; i++)
        array[i] = i + 1;
// Printing out
for(int i = 0; i < 5; i++)
    cout << array[i] << " ";
    
// Deallocating the memory
delete[] array;
Output:
1 2 3 4 5

As you can see, we dynamically reserved space in the memory for 5 integers, using a for loop to fill in those spaces in the memory, printed them out, and then deleted the array with delete[] for safe deallocation and avoiding memory leaks.

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

On input, you will be given a number N representing the number of elements for an array. Dynamically create an array called numbers using a pointer and allocate space for N integers. On the next line of input, you will be given N elements input each of them using a for loop and finally print out all of the elements on even positions (starting index is 0). Finally, deallocate the memory you allocated in the beginning

Input
5
1 2 3 4 5

Output
1 3 5

Try it yourself

#include <iostream>

using namespace std;

int main() {
    // Write code here
    return 0;
};

All lessons in C++ Pointers