KHe*_*kus 7 c++ arrays constructor
我有一个问题,我的代码在试图使用列表的size()函数时发生了分歧.根据stackoverflow的建议:-)我构建了一个最小的情况,其中发生了segfault(在下面的调用inventory.size()上).它是:
#include <list>
class Thing {};
class Player {
private:
int xpCalcArray[99];
std::list<Thing*> inventory;
public:
Player();
int addToInv(Thing& t); // return 1 on success, 0 on failure
};
Player::Player() {
// set up XP calculation array
for (int i=1; i<100; i++) {
if (i<=10) {
xpCalcArray[i] = i*100;
}
if (i>10 && i<=50) {
xpCalcArray[i] = i*1000;
}
if (i>50 && i<=99) {
xpCalcArray[i] = i*5000;
}
}
}
int Player::addToInv(Thing& t) {
if (inventory.size() == 52) {
return 0;
} else {
inventory.push_back(&t);
}
return 1;
}
int main(int argc, char *argv[]) {
Thing t;
Player pc;
pc.addToInv(t);
return 1;
}
Run Code Online (Sandbox Code Playgroud)
我注意到当我在Player cosntructor中删除数组的设置时,它工作正常,所以这看起来是问题所在.我究竟做错了什么?
您正在访问数组的边界之外。这样做会导致未定义的行为,因此对于之后发生的任何事情都没有逻辑解释。数组的大小是 99,因此最后一个索引是 98。for但是,您的循环会上升到 99。
要么将数组大小设置为 100:
int xpCalcArray[100];
Run Code Online (Sandbox Code Playgroud)
或者将您的for条件更改为i < 99.
| 归档时间: |
|
| 查看次数: |
175 次 |
| 最近记录: |