1

I am trying to create an array of Object pointers in order to sort some data. Here is my code:

ArrayClass<Exoplanet*> exoplanets;
int count = 0;
for (int i = 0; i < exosystems.size(); ++i) {
    ArrayClass<Exoplanet> *temp = exosystems.at(i)->getPlanets();
    for (int k = 0; k < temp->size(); ++k) {
        exoplanets.add(&temp->at(k));
    }
    temp->~ArrayClass();
}
//check to see if pointer array is working properly
for (int i = 0; i < exoplanets.size(); ++i) {
    exoplanets.at(i)->printPlanet();
    cout << endl;
}

ArrayClass<Exoplanet> *Exosystem::getPlanets(void) const
{
    return planets;
}

Also the getPlanets() function is included at the end for reference. Whenever I print the planets in the last for loop, all of the exoplanet pointers point to the last exoplanet returned from the getPlanet() function the final time through the 1st for loop. I think this has something to do with exoplanets.add(&temp->at(k)), but I am not sure how to fix it. Thanks in advance

Jonathan B
  • 11
  • 1
  • Why are you *destroying* the array? The `Exosystem` will miss it when it's gone (actually, your program will probably crash when it's destroyed a second time later). Also, don't store pointers into a collection, *especially* a collection that you're going to destroy. – molbdnilo Oct 13 '15 at 22:40
  • 2
    You haven't given a ["Minimal, Complete, Verifiable Example"](http://stackoverflow.com/help/mcve)...which you should always do. We don't have a definition of ArrayClass or Exoplanet. But it looks to be that you are probably freeing the memory that the planet you are adding lives in, and doing it in a very likely misunderstood way (who told you to do `temp->~ArrayClass()`?) See ["Is calling a destructor manually always the sign of a bad design"](http://stackoverflow.com/questions/14187006/). Odds are you're adding a pointer to memory that is being recycled, plus bad by the time of your loop. – HostileFork says dont trust SE Oct 13 '15 at 22:40
  • Minimize your problems and read up on **smart pointers**. Some smart pointers will take care of deleting the target object for you. – Thomas Matthews Oct 13 '15 at 22:47
  • You may want to replace `ArrayClass` with `std::vector`. – Thomas Matthews Oct 13 '15 at 22:48

0 Answers0