Menelaos Kotsollaris
Menelaos Kotsollaris

Reputation: 5506

Array of Objects Initialization (C++)

Hey guys i am i am new to C++ and through to a project i have in the university i am having some difficult times . More spesificaly : i ve created a code for Lists and Queues (Lists name = Chain , Queues name = Queue , Product is a struct that has basicly Chains fields) [btw i ve used Sahnis book (data structures) if anyone knows it. I am stuck here :

int k=4;
Queue<Chain<Product>*>* x = new Queue<Chain<Product>*> [k];
for(int i=1;i<k;i++)
{
   x[i] = new Queue<Chain<Product>*> [i+1];
}

on the loop it throws me error : Invalid conversion from Queue*>* to int

Any idea?

Upvotes: 0

Views: 755

Answers (2)

user1241335
user1241335

Reputation:

In the line x[i] = new Queue<Chain<Product>*> [i+1] he [i+1] is wrong.
Why? Well you're creating a new object new keyword. and .operator[int x] is used in arrays. In that line you are saying it should be a new Array of size i+1 of type Queue<Chain<Product>*> which is faulty. Instead use x[i] = Queue<Chain<Product>*>();

So end code is:

for(int i=0;i<k;i++)//because indexes begin at 0, not 1.
{
  x[i] = Queue<Chain<Product>*>()
}

Note* to see a simplified version of your mistake, see other guy's post (I won't copy code around - wastes space).

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258568

It should be

for(int i=0;i<k;i++)   // first index is 0
{
   x[i] = Queue<Chain<Product>*>();
}

because

Queue<Chain<Product>*>* x = new Queue<Chain<Product>*> [k];

creates an array of Queue<Chain<Product>*> objects, not pointers.

Or if you want a 2-d array, you use:

Queue<Chain<Product>*>** x = new Queue<Chain<Product>*> * [k];
for(int 0=1;i<k;i++)
{
   x[i] = new Queue<Chain<Product>*> [i+1];
}

To simplify, you're basically attempting the following:

int* x = new int[4];
for ( int i = 0 ; i < 4 ; i++ )
   x[i] = new int[i];

which is obviously wrong.

Upvotes: 2

Related Questions