#include <stdio.h>
#include <stdlib.h>
int main()
{
unsigned char **T;
int i,j;
int H[256];
FILE *fp=fopen("Collines400300.ima","rb");
T=(unsigned char**)malloc(300*sizeof(unsigned char*));
for(i=0;i<400;i++);
T[i]=(unsigned char*)malloc(400*sizeof(unsigned char));
while(fp)
{
fread(T[i],1,400,fp);
}
for(i=0;i<256;i++)
H[i]=0;
for(i=0;i<400;i++)
{
for(j=0;j<300;j++)
H[T[i][j]]++;
}
for(i=0;i<256;i++)
printf("%d ",H[i]);
return 0;
}
我试图读取长度为300和宽度为400的灰度图像的数据并将其加载到2D阵列。然后获取该数据并从中制作直方图。我没有收到任何编译错误,但我似乎无法阅读这些信息。谁能告诉我我做错了什么?谢谢。
答案 0 :(得分:3)
你有几个问题;惊讶你没有得到段错误。
//This line creates an array of char *'s of size 300
T=(unsigned char**)malloc(300*sizeof(unsigned char*));
//this line is bad... the ; at the end means this is the entire loop. This is equivalent to i = 400;
for(i=0;i<400;i++);
//this is not part of the foor loop, so you do T[400] which is outside both the bounds you may have wanted (400) and the bounds you set(300)
T[i]=(unsigned char*)malloc(400*sizeof(unsigned char*));
while(fp)
{
//this will just keep overwriting the same line.
fread(T[i],1,400,fp);
}
这应该会更好一点:
int height = 300;
int width = 400;
T=(unsigned char**)malloc(height*sizeof(unsigned char*));
for(i=0;i<height;i++)
{
if (feof(fp))
{
//handle error... could just malloc and memset to zero's
break;
}
T[i]=(unsigned char*)malloc(width*sizeof(unsigned char*));
fread(T[i],1,400,fp);
}