Gargee Suresh
Gargee Suresh

Reputation: 319

How is memory allocated in this line of code "int **v = new int*[n]; "?

 int **v = new int*[n];

I'm confused as to what this does? could someone please explain?

Upvotes: 1

Views: 107

Answers (2)

user12450543
user12450543

Reputation:

it's not correctly complete:

int **v = new int*[n];

we'd think this means to allocates dynamically array of integer array on memory, so the dimension must suit it

statically equivalent

const size_t n=5;
int *v[n] = {} ;

// or int v[][n] ={ {1,2,3,4,5}, {6,7,8}, {9,8,7,6,5} }; //2 dimensional array

as max size of first dimension is inferred automatically to be 3 but
I guess IMHO, this is not yet given,

int **v = new int*[n];

so it'd be specified as

int **v = new int*[n * 3];

Upvotes: 0

Erlkoenig
Erlkoenig

Reputation: 2754

This allocates an array of n pointers to int. A pointer to the first element in this array of pointers is stored in v. It is a double pointer, such that accessing an element via v[i] returns a stored pointer from the array.

Upvotes: 3

Related Questions