code:- p = new int *[5];
where p is a pointer & declared as int **P;
Please explain me that why there is a *
in between new and [5].

- 59
- 1
- 1
- 11
-
4Better use of your time: learn about smart pointers and containers. – Jesper Juhl May 15 '20 at 16:50
-
@Molybdenum Oxide Looks like the multiply operator. – Vlad from Moscow May 15 '20 at 16:53
-
2`p = new *[5];` is not valid code - it should be `p = new int*[5];`. – Adrian Mole May 15 '20 at 16:53
-
I have edited, review now.\ – MolyOxide May 15 '20 at 16:57
-
Remember in C++, by virtue of its C roots, pointers and arrays are interchangeable. – tadman May 15 '20 at 16:59
-
You probably should show a little more code but still less than 20 lines. [mcve] – drescherjm May 15 '20 at 16:59
-
@tadman what do you mean by pointers and arrays are interchangeable. – MolyOxide May 15 '20 at 17:08
-
@MolybdenumOxide I've added an example in my answer. – tadman May 15 '20 at 17:09
1 Answers
When allocating an array using new
you need to specify the type. The general pattern is:
type* x = new type[n];
Where type
is the base type, x
is the variable, and n
is the number of entries. You can make this a pointer type by adding *
to both sides:
type** x = new type*[n];
You can continue this indefinitely:
type**** x = new type***[n];
Though in practice you'd rarely see that since excessively deep structures like that are nothing but trouble.
In C++, by virtue of its C heritage, pointers and arrays are interchangeable, as in both these definitions are basically equivalent:
void f(int* x)
void f(int x[])
Internally you can use x
as either a pointer or an array, or both:
int y = x[0];
int z = *x;
Likewise these are identical:
int y = x[1];
int z = *(x + 1);
In general the distinction between x[n]
and *(x + n)
is largely irrelevant, the compiler treats both as the same and the emitted machine code is identical. The []
notation is just a syntax element that helps make the code easier to follow.

- 208,517
- 23
- 234
- 262