Creating dynamic allocated array of pointers

how to create array of pointer with dynamic allocation?

I want to change this following code:

const int NUM =5;

int *arrPtr[NUM] = {nullptr,nullptr,nullptr,nullptr,nullptr};


to the way using dynamic allocation. I trited this way but didn't work:

int size;
cout<<"Enter size of array"<<endl;
cin>>size
int *arrPtr =nullptr;
arrPtr = new int[size];
for(int i=0; i<size; i++)
{
arrPtr[i]=nullptr;
}


but it doesn't work. what is wrong with my code?
A dynamic array's start location is stored in a pointer.
If the array contains pointers, then it will be a double-pointer (which is just a pointer whose "pointee's" type also happens to be a pointer).
So you need a int** for the array pointer and int*[size] for the type of the allocated elements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main() {

    int size;
    cout << "Enter size of array: ";
    cin >> size;

    int** a = new int*[size];
    for (int i = 0; i < size; i++)
        a[i] = nullptr;

    delete[] a;
}

Last edited on
Thanks a lot !
Topic archived. No new replies allowed.