0
好的,所以我一直在做一個項目,並且遇到了這個問題。運行我的程序時,我得到這個消息:圖像加載功能不起作用
Unhandled exception at 0x76fa15de in programmingproj.exe: 0xC0000005: Access violation reading location 0x00000000.
這裏是Visual Studio中說,代碼中的錯誤:
float **LoadImg(const char *filename)
{
float **data = { 0 };
char *buf = new char[32];
std::string buf2;
std::ifstream filebuf(filename);
filebuf.getline(buf, 32);
// Reiterate over each pixel, very inefficient, needs to be fixed.
for (int x = 0; x < (IMAGE_SIZE_X - 1); x++)
{
for (int y = 0; y < (IMAGE_SIZE_Y - 1); y++)
{
filebuf.getline(buf, 32);
// Only copy the values.
for (int i = 8; i < 32; i++)
{
if (buf[i] != '\t' && buf[i] != ' ')
{
buf2 += buf[i];
}
}
// Set the pixel's value.
data[x][y] = (float)strtodbl(buf2);
}
}
filebuf.close();
return data;
}
這裏是我想要閱讀的格式樣本:
x y Value
1 1 0
1 2 0
1 3 0
1 4 0
1 5 10.159
1 6 5.225
1 7 1.337
1 8 0
1 9 0
1 10 0
我只需要將值字段加載到適當的像素(x,y)。
strtodbl函數只是我寫的一個快速的東西來替換atof和/或strtod。
編輯: IMAGE_SIZE_X和IMAGE_SIZE_Y只是圖像大小(97x56)的常量。
'float ** data = {0};'< - 這是罪魁禍首。改爲使用'new float [y];'然後'data [i] = new float [x]'。 –
儘管與你的崩潰無關,你應該記住圖像是二進制數據,所以你應該以二進制模式打開文件。 –
爲什麼你不這樣做:'char buf [32];'float data [IMAGE_SIZE_X] [IMAGE_SIZE_Y];' – mr5