C ++指针错误(访问冲突)

c++ pointer error (access violation)

我是 C++ 的新手,我想我可能正在做一些我不应该用指针做的事情。我已经检查了大量资源,但找不到问题所在。调试了一会儿,好像是问题代码。

writeHeader(outFile, width, height); 
for (int row=0; row < width+1; row++){ // row == 0 is the bottom row
    for (int col=0; col < height+1; col++){ // col == 0 is the leftmost column
    Color c =  getPixel(row, col);
    outFile.write((char*)c.blue, 1);
    outFile.write((char*)c.green, 1);
    outFile.write((char*)c.red, 1);
    }
}

谁能看出哪里出了问题?

getPixel 方法如下所示。

Color BMPCanvas::getPixel(int x, int y){
if (x<=width && y<=height){
        return image[y*width + x];
    }
    return Color(0,0,0);
}

编辑:我将上面的代码更改为:

    for (int row=0; row < width; row++){ // row == 0 is the bottom row
        for (int col=0; col < height; col++){ // col == 0 is the leftmost column
        Color c =  getPixel(row, col);
        unsigned char green = c.green, blue = c.blue, red = c.red;
        outFile.write((char*)&blue, 1);
        outFile.write((char*)&green, 1);
        outFile.write((char*)&red, 1);
        }
    }

我认为这解决了其中一个问题,但我仍然遇到内存错误。绿色蓝色和红色指的是数字,指的是它们的颜色值,例如 (255,255,255).

非常感谢您的帮助。

我最好的猜测是你有一个 "off by one" 错误。 C++ 数组是从零开始的,所以当你有一个有 10 个槽的数组时,你从 0 迭代到 9,而不是 0 到 10。

尝试将 getPixel 更改为:

Color BMPCanvas::getPixel(int x, int y){
if (x<width && y<height){
        return image[y*width + x];
    }
    return Color(0,0,0);
}

还有你的另一个循环:

for (int row=0; row < width; row++){ // row == 0 is the bottom row
    for (int col=0; col < height; col++){ // col == 0 is the leftmost column