0

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 *[]'

MHMD
  • 1
  • 4
  • Can you give us a bit more details how "doesn't work" is showing up? Error message, behaviour, etc - you do not use the array in your code, so what is the expected behaviour and what the observed? – cyberbrain Apr 13 '22 at 20:48
  • here it is the array in line 9, ``` int *arrp[size]; ``` ( I want to make an array of pointers) The error of the first code is that the size must be constant, I tried to fix that by writing the 2nd code but 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 *[]' – MHMD May 10 '22 at 09:23
  • The only way it worked for me was `int** arrp = new int*[size];` but cannot explain why you can't use `int*[]` in the declaration, so not posting it as an answer. But as an array is referenced with a pointer, you cannot assign an array of int (`new int[bla]`) to an array of pointers. – cyberbrain May 11 '22 at 14:09
  • Thanks, that was beneficial – MHMD Jun 02 '22 at 16:18

1 Answers1

0

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.

MHMD
  • 1
  • 4