我剛剛開始用C++編程,並且遇到了從我定義的結構中訪問數組的問題。從struct中訪問數組會崩潰程序
我正在使用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);
有一個單獨的結構,稱爲屏幕,其使用圖像實例來初始化:
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);
當我訪問寬度或高度變量時,它會得到正確的值。我這時屏幕實例傳遞給該方法:
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)
指針是相當新的給我,我不知道傳遞指針,以結構或任何規則像那樣。
假設傑克是正確的,你的誤解不是關於結構中指針的傳遞,而是關於對象的生命週期。看起來您的圖片數據在您仍然嘗試使用時已被破壞。 – john
是的,這只是因爲我習慣了Java。在Java中,只有在程序中沒有任何地方引用它時,該對象纔會被銷燬。 – CryoGenesis
嘗試將Java思想應用於C++通常會出現可怕的錯誤,儘管語法相似,但語言差異很大。 – john