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

时间:2015-02-06 02:54:58

标签: c++ pointers 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)。

我非常感谢你的帮助。

1 个答案:

答案 0 :(得分:2)

我最好的猜测是你有一个“一个接一个”的错误。 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
相关问题