How to make an array of pointers and make the user enter the size of it?

36 views Asked by At

I want to make an array, and inside this array there are pointers, like this: int *arrp[size]; and I want the user to enter the size of it. I tried to do this:

#include <iostream>
using namespace std;

int main ()
{
   int size;
   cout << "Enter the size of the array of pointers" << endl;
   cin >> size;
   int *arrp[size];
   
   return 0;
}

but this doesn't work. I also tried to do this:

#include <iostream>
using namespace std;

int main ()
{
   int size;
   cout << "Enter the size of the array of pointers" << endl;
   cin >> size;
   int* arrp[] = new int[size];
   
   return 0;
}

also doesn't work, can someone help?

The error of the first code is that the size must be constant, I tried to fix that by writing the 2nd code but it gives an error for the word "new" in line 9: E0520 initialization with '{...}' expected for aggregate object and another error for the size in the same line: C2440 'initializing': cannot convert from 'int *' to 'int *[]'

1

There are 1 answers

0
MHMD On BEST ANSWER

To make an array of pointers you should type: int** arr = new int*[size] we type 2 stars '*', the first mean a pointer to an integer, the second means a pointer to the pointer to the integer, and then we make a place in the memory for those pointers by typing = new int*[size], you can use this as a 2D array that stored in the heap (not the stack) go to this website to know the difference: https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/. to know more about how to use an array of pointers to a pointer to an integers you can see this video: https://www.youtube.com/watch?v=gNgUMA_Ur0U&ab_channel=TheCherno.