【发布时间】:2014-04-08 06:04:36
【问题描述】:
我正在尝试将 BMP 文件的像素值存储在 2D 动态分配的结构数组中,但它不断给出分段错误。到目前为止,这是我所拥有的:
#include <stdio.h>
#include <stdlib.h>
typedef struct PIXEL{
unsigned char Red, Green, Blue;
}*pixel;
int main (int argc, char *argv[])
{
//variable declarations and open the file
FILE* fin = fopen(argv[1], "rb");
if (fin == NULL){
printf("Error opening file.\n");
exit(0);
}
unsigned char info[54];
int width, height, i, j;
fread(info, sizeof(unsigned char), 54, fin); //read the header
width = *(int*)&info[18];
height = *(int*)&info[22];
pixel **image = (pixel **) malloc(sizeof(pixel *) * width); //reserve enough space for RGB for each pixel
for (i = 0; i < width; i++){
image[i] = (pixel *) malloc(sizeof(pixel) * height);
}
for (i = 0; i < width; i++){
for (j = 0; j < height; j++){
image[i][j]->Blue = getc(fin); //put the blue value of the pixel
image[i][j]->Green = getc(fin); //green value
image[i][j]->Red = getc(fin); //red value
printf("Pixel %d: [%d, %d, %d]\n", (i+1)*(j+1), image[i][j]->Blue, image[i][j]->Green, image[i][j]->Blue);
}
}
fclose(fin);
return 0;
}
【问题讨论】:
-
printf 行应该有 image[i][j]->Red 而不是 image[i][j]->Blue 两次
-
它给你的错误是哪一行?使用像 Visual Studio Express 这样的简单调试器来逐步执行您的代码。还可以尝试使用非常小的 10 x 10 像素位图来干运行代码。
-
啊,发现是打开bmp文件出错
-
在 printf 中要小心。您指定 %d 格式但给出无符号字符。这可能很危险,请改为向 (int) 添加强制转换