为什么这个指针-指针初始化段错误?
我创建了一个类对象的指针到指针,当我尝试使用该指针创建一个新对象时,它会出现段错误。 为什么会出现这种情况?
struct Level
{
int SoldierCount;
Soldier **soldier;
int taskCount;
int *taskPercentage;
int *taskBitmapX;
int *taskBitmapY;
}level;
void createMap()
{
//Input and Declartion of various variabls goes here
level.soldier = new Soldier* [level.SoldierCount];
//Seg Faults Here
level.Soldier[i] = new Soldier(initX, initY, initDirection, steps);
}
士兵类构造函数:
Soldier(int, int, int, int);
I create a pointer-to-pointer of a class object and when I try to create a new object using the pointers it seg-faults. Why does this happen?
struct Level
{
int SoldierCount;
Soldier **soldier;
int taskCount;
int *taskPercentage;
int *taskBitmapX;
int *taskBitmapY;
}level;
void createMap()
{
//Input and Declartion of various variabls goes here
level.soldier = new Soldier* [level.SoldierCount];
//Seg Faults Here
level.Soldier[i] = new Soldier(initX, initY, initDirection, steps);
}
The Soldier Class Constructor:
Soldier(int, int, int, int);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用空的
Soldier
构造函数,您的代码可以正常工作(除了更正的拼写错误,例如小写的level.soldier[]
),请发布构造函数主体。
With empty
Soldier
constructor your code works fine (except for corrected typos, like lowercaselevel.soldier[]
)Please post the constructor body.
我在您的代码中找不到任何与段错误相关的问题。
但我很困惑为什么你的区分大小写不匹配:
该类称为“Soldier”,Soldier** 称为“soldier”。
但是你写:
和:
如果代码确实按照你编写的那样编译,这可能就是问题所在。
I can not find any segfault related problems in your code.
But I'm confused as to why your case sensitivity does not match:
The class is called "Soldier" and the Soldier** is called "soldier".
But you write:
and:
If the code really compiles as you've written it, this could be the problem.
可能
i >= level.SoldierCount
?Possibly
i >= level.SoldierCount
?level.SoldierCount
的值是多少?i
的值是多少 发生段错误的唯一原因是访问未分配的内存。 在您突出显示的行中,唯一可能发生的地方是在数组中(或在构造函数内部,您没有发布其代码)。 最有可能的是,您正在越界访问数组。
What is the value of
level.SoldierCount
?What is the value of
i
The only way a segfault can occur is if you access unallocated memory. In the line you highlighted, the only place that can happen is in the array (or inside the constructor, which you didn't post the code for). Most likely, you're accessing the array out of bounds.