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].
I encountered some thing weird code in Dynamic memory allocation for 2D arrays in C++? please explain me what is this?
91 views Asked by MolyOxide At
1
When allocating an array using
new
you need to specify the type. The general pattern is:Where
type
is the base type,x
is the variable, andn
is the number of entries. You can make this a pointer type by adding*
to both sides:You can continue this indefinitely:
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:
Internally you can use
x
as either a pointer or an array, or both:Likewise these are identical:
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.