[英]Reading binary data from a file
#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;
}
I am attempting to read data of a gray scale image of length 300 and width 400 and load it to a 2D array. 我正在尝试读取长度为300且宽度为400的灰度图像的数据并将其加载到2D数组中。 Then take that data and make a histogram out of it.
然后获取该数据并从中制作直方图。 I am not getting any compilation errors but I can't seem to read the information.
我没有收到任何编译错误,但似乎无法阅读该信息。 Can anyone tell me what I am doing wrong?
谁能告诉我我在做什么错? Thank you.
谢谢。
You have a couple of issues; 你有几个问题; surprised you didn't get a segfault.
感到惊讶的是您没有遇到段错误。
//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);
}
This should work a bit better: 这应该工作得更好:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.