指针到指针在调用函数时EXC_BAD_ACCESS
Pointer to pointer gets EXC_BAD_ACCESS when calling function
我有两个类,一个叫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;
}
}
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- 为什么这个例子在指针上"bad!"?