简体   繁体   中英

Pointer to pointer gets EXC_BAD_ACCESS when calling function

I have two classes, one called Handler and one called Dice . In my Handler class i have a private variable called Dice **dices and a public function called rollDices . And in my Dice class i have a function called toss that will randomize a number 1-6. The problem is that when the function rollDices is calling the function toss I get EXT_BAD_ACCESS in toss function. Does anyone know why, and have a solution for it?

My Handler.cpp:

void Handler::rollDices(){
    Dice **allDices = new Dice*[this->nrOfDices];
    this->dices = allDices;
    dices[nrOfDices]= new Dice(nrOfDices);
    int count =1;
    for (int i = 0; i < this->nrOfDices; i++)
    {
        allDices[i]->toss();
        cout << "Dice "<< count << ": " << allDices[i]->getValue() << endl;
        count ++;
    }
}

My Dice.cpp:

void Dice::toss(){
    this->value = rand()%this->nrOfSides+1; //Value is a private int in Dice class
}

If you need more code i can post it, just tell me!

Dice **allDices = new Dice*[nrOfDices];

Allocates the top level pointer so now we have all of the rows in memory. When you add the columns

dices[nrOfDices]= new Dice(nrOfDices);

This does not add a new Dice to all of the rows. It adds a new Dice to one past the end of valid range of dices . What you need to do is use a loop and go through all of the rows and add a Dice to each one like

for (int i = 0; i < nrOfDices; i++)
    dices[i] = new Dice(nrOfDices);

You are only allocating a single Dice object at index nrOfDices (which is of bounds by the way), if you want to allocate all Dice objects you need:

void Handler::rollDices(){
    Dice **allDices = new Dice*[nrOfDices];
    this->dices = allDices;
    int count =1;
    for (int i = 0; i < this->nrOfDices; i++)
    {
        dices[i] = new Dice(nrOfDices);
        allDices[i]->toss();
        cout << "Dice "<< count << ": " << allDices[i]->getValue() << endl;
        count ++;
    }
}

How about using modern C++? Try something like this:

    void Handler::rollDice()
    {
        std::vector<Dice> allDice( nrOfDice );
        int count = 1;
        for( const auto & d : allDice )
        {
            d.toss();
            cout << "Die "<< count << ": " << d.getValue() << endl;
            ++count;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM