简体   繁体   中英

Dynamically allocating an array of pointers

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.

Its a double pointer int variable. as I see from code it code. it stores the address of pointer int*

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]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM