Tushar Saha
Tushar Saha

Reputation: 2106

Unable to understand Implementation of List in c++

If I have a statement in my c++ program as

list < int > *adj;

adj = new list < int > [V];

what does [v] mean here does it signify size of list or number of list that are being created.

Sorry for such a silly question but I searched a lot of place but without any clear answer.

Edit 1: added declaration of list

Upvotes: 0

Views: 407

Answers (4)

Steephen
Steephen

Reputation: 15824

adj = new list[V];

I hope you have a class list and it has a constructor, either default or user defined public constructor not accepting any parameter, that means it is default constructable. And V is an integer.

If you use simply list adj[V] system creates an array of list with size V, so your list constructor will get call V times.

new operator allocates memory and invokes the constructor.

So this statement list* adj= new list[V] allocates memory for V times the size of object of class list and invokes constructor of class list V times, and assigns the starting of the memory location to variable adj.

So to deallocate and destruct all V objects of list that you have created, you should call delete as follows

delete [] adj;

Upvotes: 1

kiviak
kiviak

Reputation: 1103

new list[V] means you create an list type array of length V


new is an Operator of c++,it works blow:

  1. malloc rooms: malloc(sizeof(list)*V)
  2. do some Initializations: call default construct function to Initializat each value in the array`
  3. give the pointer of the array

`

Upvotes: 1

Emil Laine
Emil Laine

Reputation: 42838

It's called the new[] operator.

It allocates and initializes memory for a list array with size V, and returns a list pointer pointing to the first element of the array.

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227418

This kind of expression

new X[N]

allocates an array of type X and length N, and evaluates to a pointer to its first element.

This kind of statement

x = new X[N];

assigns the result of the expression on the right hand side of the = to x.

So, you are dynamically allocating an array of V objects of type list, ans assigning a pointer to the first element to adj.

This has nothing to do with the implementation of list.

Upvotes: 1

Related Questions