How does the last line of code dynamically allocate an array of pointers?
int size;
cin >> size;
int** arr = new int* [size];
I am most unclear about the 'int**' part of the code. Can someone break this down?
Thanks!
int a; // a is an int
int *a; // a is a pointer to an int
int **a; // a is a pointer to a pointer to an int
You can make a int* point to an array of int, like this:
int *a = new int[42]; // allocates memory for 42 ints
Exactly the same way, you can make an int** point to an array of int*, like this:
int **a = new int* [42]; // allocates memory for 42 int*
Note that each of the pointers in this array needs to be allocated its own memory, otherwise you just have an array of 42 pointers, none of which are pointing to valid memory.
To create a dynamic array the syntax is : data_type * name_of_array = new data_type [size] you can make size as a variable or value as you like .
Think of it like this:
To allocate an array you use a type *_var = new type[size]
But you want your type to be pointer to int so: int* *arr = new (int*)[size]
int* arr = new int[size]allocates an array ofints. It's just that instead ofintyou haveint*.