我正在尝试从 bmp 文件中提取 RGB 组件,但是当它到达Data[i][j].Blue
时我遇到了 seg 错误。我尝试打印出三种颜色的十六进制,它打印出来很好,但随后它打印出所有 RGB 组件都0xFF,然后在它变成蓝色时出现错误。我得到的任何帮助都非常感谢。
int inputColors(char *filename, struct INFOHEADER *InfoHeader, struct PIXEL **Data){
int i = 0, j = 0;
FILE *inputFile;
printf("The height of the picture is %dn", InfoHeader->Height);
printf("The width of the picture is %dn", InfoHeader->Width);
if((inputFile = fopen(filename, "r")) == NULL){
printf("Unable to open .bmp filen");
exit(1);
}
//Mallocing enough space for the 2D structures of pixels (colors)
Data = (struct PIXEL **)malloc(InfoHeader->Width * sizeof(struct PIXEL *));
for(i = 0; i < InfoHeader->Height; i++){
Data[i] = (struct PIXEL *)malloc(InfoHeader->Height * InfoHeader->Width * sizeof(struct PIXEL));
}
//This goes until after we are down with the header
fseek(inputFile, 54, SEEK_SET);
//Inputing the data into the malloced struct
i = 0;
for(i = 0; i < InfoHeader->Height; i++){
for(j = 0; j < InfoHeader->Width; j++){
Data[i][j].Red = getc(inputFile);
// printf("The Red componet is %Xn", Data[i][j].Red);
Data[i][j].Green = getc(inputFile);
// printf("The green componet is %Xn", Data[i][j].Green);
Data[i][j].Blue = getc(inputFile);
// printf("The blue componet is %Xn", Data[i][j].Blue);
}
}
fclose(inputFile);
return 0;
}
对于初学者来说,你的第一个malloc使用
。InfoHeader->Width * sizeof(struct PIXEL *)
但是,在迭代数组时,您可以使用 InfoHeader->Height。 由于这种不匹配,如果 InfoHeader->Width 小于 InfoHeader->Height,则它不会分配足够的内存来执行迭代,并且会出错。
Data = (struct PIXEL **)malloc(InfoHeader->Width * sizeof(struct PIXEL *));
// ^^^^^
for(i = 0; i < InfoHeader->Height; i++){
// ^^^^^^
Data[i] = (struct PIXEL *)malloc(InfoHeader->Height * InfoHeader->Width * sizeof(struct PIXEL));
}