我正在尝试从.bmp图像文件中读取数据,以便可以对其进行操作。但是,读完数据后,我发现两个我认为是相关的问题。首先,在调用fclose()时我得到了一个sigabrt,其次,如果我简单地注释掉了fclose(),即使读入结构正确,我读入结构数组的所有数据都设置为255。我对C很陌生,所以这几乎肯定是菜鸟在分配动态内存上的错误。
Pixel** readFile(FILE* fp,Header* header,InfoHeader* infoHeader)
{
if(fp == NULL)
{
printf("file not found\n");
return NULL;
}
fread(&header->Type,SHORTSIZE,1,fp);
fread(&header->Size,INTSIZE,1,fp);
fread(&header->Reserved1,SHORTSIZE,1,fp);
fread(&header->Reserved2,SHORTSIZE,1,fp);
fread(&header->Offset,INTSIZE,1,fp);
fread(&infoHeader->Size,INTSIZE,1,fp);
fread(&infoHeader->Width,INTSIZE,1,fp);
fread(&infoHeader->Height,INTSIZE,1,fp);
fread(&infoHeader->Planes,SHORTSIZE,1,fp);
fread(&infoHeader->Bits,SHORTSIZE,1,fp);
fread(&infoHeader->Compression,INTSIZE,1,fp);
fread(&infoHeader->ImageSize,INTSIZE,1,fp);
fread(&infoHeader->xResolution,INTSIZE,1,fp);
fread(&infoHeader->yResolution,INTSIZE,1,fp);
fread(&infoHeader->Colors,INTSIZE,1,fp);
fread(&infoHeader->ImportantColors,INTSIZE,1,fp);
int rows = infoHeader->Height;
int cols = infoHeader->Width;
Pixel** pixelArr = malloc(rows * sizeof(Pixel*));
int i;
for (i = 0; i < cols; i++)
{
pixelArr[i] = (Pixel*) malloc(sizeof(Pixel));
}
int j;
for(i = 0; i < rows; i++)
{
for(j = 0; j < cols; j++)
{
fread(&pixelArr[i][j].Red,CHARSIZE,1,fp);
fread(&pixelArr[i][j].Green,CHARSIZE,1,fp);
fread(&pixelArr[i][j].Blue,CHARSIZE,1,fp);
}
printf("\n");
}
fclose(fp);
return pixelArr;
}