How to use the new keyword In C++

The new Keyword in C++ represents dynamic memory allocation i.e, heap memory. The code will suffer from a memory leak if the programmer does not free up the memory before exiting. This can lead to a huge problem in long-running applications or resource-constrained hardware environments.

Syntax:

int **arr=new int*[size_of_array];

Example:

C++




// c++ Program to create
// vector pointer
// using new keyword (dynamic array)
#include <iostream>
#include <vector>
using namespace std;
 
void print_vector(int** ptr, int n)
{
    cout << "Elements are: ";
 
    // printing the values of the array
    for (int i = 0; i < n; i++) {
        cout << **(ptr + i) << " ";
    }
 
    cout << endl;
}
 
void remove_element(int** ptr, int* n)
{
    int pos = *n - 1;
 
    // releasing the element from the array
    delete ptr[pos];
 
    // decreasing the size of array
    (*n)--;
}
 
int main()
{
 
    cout << "Enter size of array: ";
    // declaring size of array;
    int n;
    cin >> n;
 
    // declaring dynamic array
    int** ptr = new int*[n];
 
    cout << "Enter elements of array:";
 
    // inserting elements in array
    for (int i = 0; i < n; i++) {
 
        // declaring a variable to store in array
        int a;
        cin >> a;
 
        // Inserting the declared variable in the array
        *(ptr + i) = new int(a);
    }
 
    cout << "Array Before removing element\n";
    print_vector(ptr, n);
 
    // remove last element from array
    remove_element(ptr, &n);
 
    cout << "Array After removing element\n";
    print_vector(ptr, n);
 
    // removing all elements of array
    for (int i = 0; i < n; i++) {
        delete ptr[i];
    }
 
    // releasing array
    delete ptr;
}


Output:

Enter size of array: 5
Enter elements of array: 5 4 3 2 1
Array Before removing element
Elements are: 5 4 3 2 1
Array After removing element
Elements are: 5 4 3 2


C++ Vector of Pointers

Prerequisites

Vector of pointers are vectors that can hold multiple pointers. Each pointer within a vector of pointers points to an address storing a value. We can use the vector of pointers to manage values that are not stored in continuous memory.

Similar Reads

How to Create Vector of Pointers in C++?

Similar to any other vector declaration we can declare a vector of pointers. In C++ we can declare vector pointers using 3 methods:...

1. Using std::vector container

Using vectors to create vector pointers is the easiest and most effective method as it provides extra functionality of STL....

2. Using [ ] notations

...

3. Using the new keyword

Square brackets are used to declare fixed size. This can be used to operate over to create an array containing multiple pointers. This is a type of array that can store the address rather than the value. So, can be called a pointer array, and the memory address is located on the stack memory rather than the heap memory....