从struct访问数组会使程序崩溃

时间:2013-08-27 20:47:01

标签: c++ arrays opengl

我刚刚开始用C ++编程,我遇到了从我定义的结构访问数组的问题。

我正在使用OpenGL使用纹理将一组像素数据绘制到屏幕上。像素数据数组存储在Image结构中:

struct Image {

GLubyte *pixels;
int width;
int height;
int bitrate;

Image(int w, int h, GLubyte* pixels, int bitrate){
    this->width = w;
    this->height = h;
    this->pixels = pixels;
    this->bitrate = bitrate;
}

};

图像初始化如下:

GLubyte* pix = new GLubyte[WIDTH*HEIGHT*3];
Image image(WIDTH, HEIGHT, pix, 3);

有一个名为Screen的独立结构,它使用Image实例初始化:

    struct Screen{

    int width, height;
    Image* screen;

    void setScreen(Image* screen, const int width, const int height){
        this->screen = screen;
        this->width = width;
        this->height = height;
    }

};

屏幕初始化如下(图像声明后):

displayData = new Screen();
displayData->setScreen(&image, WIDTH, HEIGHT);

当我访问Width或Height变量时,它会获得正确的值。然后我将屏幕实例传递给此方法:

void renderScreen(Screen *screen){
std::cout << "Rendering Screen" << std::endl;
for(int x = 0; x < screen->width; x++){
    for(int y = 0; y < screen->height; y++){

        std::cout << "rendering " << x << " " << y << std::endl;

                    //Gets here and crashes on x - 0 and y - 0

        screen->write(0xFFFFFFFF, x, y);
    }
}
std::cout << "done rendering Screen" << std::endl;
}

这样称呼:

render(displayData); (displayData is a Screen pointer)

指针对我来说是一个新手,我不知道将指针传递给结构或类似的东西的规则。

1 个答案:

答案 0 :(得分:3)

displayData->setScreen(&image, WIDTH, HEIGHT);

这似乎指出你通过获取局部变量的地址来传递指向Image的指针,例如。

void method() {
  Image image;
  displayData->setScreen(&image, ..)
}

在这种情况下,image在堆栈上分配,并且在退出声明该局部变量的作用域后,指向它的指针不再有效。

你应该在堆上分配它:

Image *image = new Image(..);
displayData->setScreen(image, ...);

以这种方式,对象将继续存在,直到您使用delete image明确删除它。

相关问题