简体   繁体   中英

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. The fp pointer is to a binary file that the data is contained there.

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). 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.

So what am i doing wrong in the memory allocation or in the use of fread? Because obviously the problem is there.

In order to make it easier lets assume that the size is 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*/ }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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