简体   繁体   English

3D 数组的内存分配和 fread 在 C 结果中的使用

[英]Memory Allocation of 3D Array and Use of fread in C results

// A part of Code
 int dim1=height;
 int dim2=width;
 int dim3=3;
    
 int k;
 
  unsigned char *** image = (unsigned char  ***)malloc(dim1*dim2*3);

        for (i = 0; i< dim1; i++) {

             image[i] = (unsigned char  **)malloc(dim2*sizeof(unsigned char  *));

          for (j = 0; j < dim2; j++) {

              image[i][j] = (unsigned char  *)malloc(dim3*sizeof(unsigned char ));
          }

        }




// B part of Code
  for (i = 0; i < height; i++) {
        
           for (j = 0; j < width; j++) {
               
                   
        fread(&image[i][j][0],sizeof(unsigned char),1,fp);
        fread(&image[i][j][1],sizeof(unsigned char),1,fp);
        fread(&image[i][j][2],sizeof(unsigned char),1,fp);
         
          
                   
         
           }
        
    }

As you can see from above I am trying to declare a 3d array that will contain the pixel information of a bmp image.从上面可以看出,我试图声明一个 3d 数组,该数组将包含 bmp 图像的像素信息。 The fp pointer is to a binary file that the data is contained there. fp 指针指向包含数据的二进制文件。

My question is how is it possible when I try to fread using dynamic memory allocation to get wrong results in image table (meaning a blank image is printed even though the rest of my code that i dont include here is correct).我的问题是,当我尝试使用动态内存分配进行 fread 以在图像表中获得错误的结果时,怎么可能(这意味着即使我没有在此处包含的其余代码是正确的,也会打印空白图像)。 On the other hand when i remove the A part of the Code and replace it with "unsigned char image[height][width][3]" it works.另一方面,当我删除代码的 A 部分并将其替换为“无符号字符图像[高度][宽度][3]”时,它可以工作。

So what am i doing wrong in the memory allocation or in the use of fread?那么我在内存分配或 fread 的使用中做错了什么? Because obviously the problem is there.因为显然问题就在那里。

In order to make it easier lets assume that the size is 252x252x3.为了方便起见,我们假设大小为 252x252x3。

typedef struct
{
    unsigned char R;
    unsigned char G;
    unsigned char B;
}RGB;

void *allocateReadImage(size_t width, size_t height, FILE *fi)
{
    RGB (*picture)[width] = malloc(sizeof(*picture) * height);

    if(picture && fi)
    {
        if(fread(picture, sizeof(*picture), height, fi) != height)
        {
            free(picture);
            picture = NULL;
        }
    }
    return picture; 
}

usage:用法:

RGB *mypicture = allocateReadImage(1600, 1200, inputfile);
if(!mypicture) { /*some error handling*/ }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM