我刚刚开始使用 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;
}
};
屏幕是这样初始化的(在 Image 声明之后):
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)
指针对我来说很新,我不知道将指针传递给结构或类似的东西的规则。