为什么这个指针-指针初始化段错误?

发布于 2024-07-13 00:55:07 字数 586 浏览 10 评论 0原文

我创建了一个类对象的指针到指针,当我尝试使用该指针创建一个新对象时,它会出现段错误。 为什么会出现这种情况?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

Spring初心 2024-07-20 00:55:07

使用空的 Soldier 构造函数,您的代码可以正常工作(除了更正的拼写错误,例如小写的 level.soldier[]),

请发布构造函数主体。

With empty Soldier constructor your code works fine (except for corrected typos, like lowercase level.soldier[])

Please post the constructor body.

千紇 2024-07-20 00:55:07

我在您的代码中找不到任何与段错误相关的问题。

但我很困惑为什么你的区分大小写不匹配:
该类称为“Soldier”,Soldier** 称为“soldier”。

但是你写:

level.soldier = new soldier* [level.SoldierCount];

和:

level.Soldier[i] = new Soldier(initX, initY, initDirection, steps);

如果代码确实按照你编写的那样编译,这可能就是问题所在。

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:

level.soldier = new soldier* [level.SoldierCount];

and:

level.Soldier[i] = new Soldier(initX, initY, initDirection, steps);

If the code really compiles as you've written it, this could be the problem.

雄赳赳气昂昂 2024-07-20 00:55:07

可能i >= level.SoldierCount

Possibly i >= level.SoldierCount?

眼眸 2024-07-20 00:55:07

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文