gpt4 book ai didi

c - 当尝试从 bmp 文件中提取 RGB 分量时,为什么我的代码段出现错误?

转载 作者:行者123 更新时间:2023-11-30 14:40:07 25 4
gpt4 key购买 nike

我试图从 bmp 文件中提取 RGB 分量,但当它到达 Data[i][j].Blue 时出现段错误。我尝试打印出三种颜色的十六进制,打印效果很好,但随后打印出所有 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 %d\n", InfoHeader->Height);
printf("The width of the picture is %d\n", InfoHeader->Width);

if((inputFile = fopen(filename, "r")) == NULL){
printf("Unable to open .bmp file\n");
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 %X\n", Data[i][j].Red);
Data[i][j].Green = getc(inputFile);
// printf("The green componet is %X\n", Data[i][j].Green);
Data[i][j].Blue = getc(inputFile);
// printf("The blue componet is %X\n", Data[i][j].Blue);
}
}

fclose(inputFile);
return 0;
}

最佳答案

首先,您的第一个 malloc 使用

InfoHeader->Width * sizeof(struct PIXEL *)

但是当你迭代数组时,你会使用InfoHeader->Height。由于这种不匹配,如果 InfoHeader->Width 小于 InfoHeader->Height,则不会分配足够的内存来执行迭代,并且会出现 SEGFAULT。

关于c - 当尝试从 bmp 文件中提取 RGB 分量时,为什么我的代码段出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55680991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com