user1802890
user1802890

Reputation: 33

To pass an array into a function

I have a class called Planet.

And I have an array of Planet objects.

I declared the array as follows:

planet * planetList[5] = 
{
  new planet(...),
  new planet(...),
  new planet(...),
  new planet(...),
  new planet(...),
};

And so I need to pass this array into these 2 functions.

For both functions, I declare them as such, with exactly the same parameters:

void function1 (planet planetList[5], int numOfPlanets) {...}
void function2 (planet planetList[5], int numOfPlanets) {...}

But when I call these 2 functions,

// receives no error
function1(planetList, numOfPlanets);
// error saying "cannot convert parameter 1 from 'planet *[5]' to 'planet []'"
function2(planetList, numOfPlanets);   

Can anyone explain this phenomenon?

Upvotes: 0

Views: 123

Answers (4)

WaffleSouffle
WaffleSouffle

Reputation: 3363

You've declared an array of planet pointers (planet * []), but the function parameters are planet object arrays (planet []). As such, neither function call should work.

Try:

void function1(planet *planetList[5], int numOfPlanets) {}
void function2(planet *planetList[5], int numOfPlanets) {}

Upvotes: 2

Mike Seymour
Mike Seymour

Reputation: 254431

I have an array of Planet objects

No, you have an array of pointers to Planet objects. An array of objects would look like:

planet planetList[5] = 
{
  planet(...),
  planet(...),
  planet(...),
  planet(...),
  planet(...),
};

That is probably what you want.

If you really want an array of pointer for some reason, then you'll need to change the functions to accept that:

void function1(planet * planetList[5], int numOfPlanets);

or equivalently

void function1(planet ** planetList, int numOfPlanets);

Can anyone explain this phenomenon?

No, both functions should fail to compile in the same way. Could you post a more complete example so we can reproduce the phenomenon ourselves?

Upvotes: 0

akash
akash

Reputation: 1801

You have an array of pointers that points to the object.You have an array of pointers that points to the object so any pointer to array of pointer will do the wrk for you
for ex
void function1 (planet *planetList[5], int numOfPlanets) {...}
void function2 (planet *planetList[5], int numOfPlanets) {...}

or

void function1 (planet **planetList, int numOfPlanets) {...}
void function2 (planet **planetList, int numOfPlanets) {...}

Upvotes: 0

Mike Dinescu
Mike Dinescu

Reputation: 55720

Try this:

void function1 (planet** planetList, int numOfPlanets) {...}
void function2 (planet** planetList, int numOfPlanets) {...}

Upvotes: 0

Related Questions