分段错误 - 改变struct(在另一个struct中)变量

时间:2012-12-12 06:02:01

标签: c++ pointers struct segmentation-fault nested

我有这个,在我的标题中:

    struct Surface {
        char *objectName;
        int xPos;
        int yPos;
        SDL_Surface *surface;
    };

    struct WorldSurface {
        Surface *surface = new Surface[MAX_SURFACES];
        int counter = 0;
        int current = 0;
    };

    WorldSurface *worldSurface;

然后我在.cpp中初始化worldSurface:

    WorldSurface *worldSurface = new WorldSurface[MAX_LEVELS];

而且这个功能,无论如何都无法开始工作,已经尝试过乱用= NULL,指针, - >而不是。... ...(请记住,我不是很精明的指针主题)

    void drawClass::addSurface(char* objectName, char* surfaceFile, int xPos, int yPos, int drawLevel) {
        int cnt = worldSurface[drawLevel].counter;
        worldSurface[drawLevel].surface[cnt].objectName = objectName;
        worldSurface[drawLevel].surface[cnt].surface = load_image(surfaceFile);
        worldSurface[drawLevel].surface[cnt].xPos = xPos;
        worldSurface[drawLevel].surface[cnt].yPos = yPos;
        worldSurface[drawLevel].counter++;
    }

这是10个worldSurfaces,每个包含50个表面结构,我想访问worldSurface [drawLevel]中的struct,我想要访问的表面结构在worldSurface中的.counter变量中是已知的。但是对于底层表面结构的所有过程都会因为分段错误而失败,我不知道为什么......

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您的WorldSurface未正确定义或初始化:

struct WorldSurface {
    Surface *surface = new Surface[MAX_SURFACES];
    int counter = 0;
    int current = 0;
};

您不能将该数据与类的声明一起初始化。您需要在构造函数中执行此操作,例如:

struct WorldSurface {
    Surface *surface;
    int counter;
    int current;
};
...
WorldSurface::WorldSurface():
    counter(0),current(0),surface(new Surface[MAX_SURFACES]){}