Reputation: 25
void solution3(){
char str[100];
int height, width;
printf("가로와 세로 길이를 입력 : ");
scanf("%d %d", &width, &height);
FILE* fp = fopen("lena_256x256.raw", "rb");
//2dynimic
unsigned char **p = new unsigned char*[height];
for(int i = 0; i < height; i++) *(p + i) = new unsigned char[width];
for(int i = 0; i < height; i++){
for(int j = 0; j < width; j++)
fread((void*)p[i][j], sizeof(unsigned char), height * width, fp);
}
//print
for(int i = 0; i < height; i++){
for(int j = 0; j < width; j++)
printf("%4d ", p[i][j]);
}
//del dynimic
for(int i = 0; i < height; i ++) delete[] p[i];
delete[] p;
fclose(fp);
}
void main(){
solution3();
}
Error message is "string != NULL" why cant read .raw file?
and I try p[i][j]
fix (void*)p[i][j]
. but can not.
I want read .raw and print info about .raw light
Upvotes: 0
Views: 894
Reputation: 8475
The code has undefined behavior here:
unsigned char **p = new unsigned char*[height]; .... fread((void*)p[i][j], sizeof(unsigned char), height * width, fp);
p
is a pointer to pointer of char. Which means that p[i][j]
is a char, which the code casts to (void*)
. This is an invalid address which fread
tries to write to.
It is likely that you want:
for(int i = 0; i < height; i++){
if (fread((void*)p[i], 1, width, fp) != width)
{
manage the error condition
}
}
Aside of that, it is not recommended to work directly with new/delete, and std::vector would be safer in this case. Also, void main()
is wrong and should be int main()
instead.
Upvotes: 4