指针到指针在调用函数时EXC_BAD_ACCESS

Pointer to pointer gets EXC_BAD_ACCESS when calling function

本文关键字:指针 BAD ACCESS EXC 函数 调用      更新时间:2023-10-16

我有两个类,一个叫Handler,一个叫Dice。在我的Handler类中,我有一个名为Dice **dices的私有变量和一个名为rollDices的公共函数。在我的Dice课上,我有一个名为toss的函数,它将随机化数字1-6。问题是,当函数rollDices调用函数抛掷时,我会toss函数中得到EXT_BAD_ACCESS。有谁知道为什么,并有解决方案?

我的处理程序.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 ++;
    }
}

我的骰子.cpp:

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

如果您需要更多代码,我可以发布它,请告诉我!

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

分配顶级指针,因此现在我们在内存中拥有了所有行。 添加列时

dices[nrOfDices]= new Dice(nrOfDices);

这不会向所有行添加新Dice。 它将新Dice添加到有效dices范围结束之后的 。 您需要做的是使用循环并遍历所有行,并为每行添加一个Dice,例如

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

如果你想分配所有你需要的骰子对象,你只在索引 nrOfDices 处分配一个骰子对象(顺便说一下,这是有界的):

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 ++;
    }
}

使用现代C++怎么样?尝试这样的事情:

    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;
        }
    }