从struct访问数组会使程序崩溃 我刚刚开始C++编程,从定义的结构中访问数组时遇到了问题。

从struct访问数组会使程序崩溃 我刚刚开始C++编程,从定义的结构中访问数组时遇到了问题。,c++,arrays,opengl,C++,Arrays,Opengl,我正在使用OpenGL使用纹理在屏幕上绘制一组像素数据。像素数据的阵列存储在图像结构中: 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; t

我正在使用OpenGL使用纹理在屏幕上绘制一组像素数据。像素数据的阵列存储在图像结构中:

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的单独结构,它使用图像实例初始化:

    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;
    }

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

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

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;
}
指针对我来说是很新的,我不知道如何将指针传递给结构或类似的东西

displayData->setScreen(&image, WIDTH, HEIGHT);
这似乎表明,通过获取局部变量的地址,您正在传递一个指向
图像的指针

void method() {
  Image image;
  displayData->setScreen(&image, ..)
}
在这种情况下,
image
被分配到堆栈上,当退出声明该局部变量的作用域时,指向它的指针不再有效

您应该在堆上分配它:

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

通过这种方式,对象将继续存在,直到您使用
delete image

显式删除它。OP选择除image变量之外的所有新对象的方式很奇怪。假设Jack是对的,您的误解不是结构中指针的传递,而是对象的生命周期。当你还在尝试使用图像数据时,它似乎已经被破坏了。是的,这只是因为我习惯了Java。在java中,对象在程序中的任何地方都没有被引用,所以它不会被破坏。尝试将java思想应用到C++通常会遇到非常错误的、非常不同的语言,尽管语法相似。
void method() {
  Image image;
  displayData->setScreen(&image, ..)
}
Image *image = new Image(..);
displayData->setScreen(image, ...);