简体   繁体   English

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

[英]c++ pointer error (access violation)

I am new to C++ and think I am probably doing something I shouldn't be with pointers. 我是C ++的新手,并且认为我可能正在做一些我不应该使用指针的事情。 I've checked tons of resources, but just can't find the problem. 我检查了很多资源,但找不到问题。 After debugging for a while it looks like this is the problem code. 经过一段时间的调试,看起来这是问题代码。

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

can anyone see what is wrong? 谁能看到哪里出了问题?

The getPixel method looks like this. getPixel方法如下所示。

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

EDIT: I changed the above code to: 编辑:我将上面的代码更改为:

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

which I believe fixed one of the problems, but I am still getting a memory error. 我相信可以解决其中一个问题,但是仍然出现内存错误。 Green blue and red refer to numbers referring to their color value such as (255,255,255). 绿色蓝色和红色是指引用其颜色值的数字,例如(255,255,255)。

I truly appreciate the help. 我非常感谢您的帮助。

My best guess would be you have an "off by one" error. 我最好的猜测是您遇到“一举两得”的错误。 C++ arrays are zero based and so when you have an array with 10 slots you iterate from 0 to 9, not 0 to 10. C ++数组是从零开始的,因此当您有一个带有10个插槽的数组时,您会从0迭代到9,而不是从0迭代到10。

Try changing getPixel to this: 尝试将getPixel更改为此:

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

And your other loop to this: 和你的另一个循环到此:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM