0

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!

1
  • 1
    Same way that int* arr = new int[size] allocates an array of ints. It's just that instead of int you have int*. Commented Jun 27, 2020 at 17:58

4 Answers 4

3
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.

Sign up to request clarification or add additional context in comments.

2 Comments

I see... so, "int** a;" is pointer which points to an "int pointer", in which that pointer (int** a) is used to dynamically allocate memory for the original "int* a", which is what the ' new int* [size] part of the code does? Am I understanding this correctly?
Yes, I think you've got it. I'm happy to clarify if you need that though.
0

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

Comments

0

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 .

1 Comment

Yes, I understand this when referring to a fundamental data type, but I was specifically asking how it works for an array of pointers.
0

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]

1 Comment

typo: type vs _type

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.