1

I'm having issues filling a 2d array of a struct inside a struct. It allows me to do it for pixels[0][1], pixels[0][2]....etc. However, once I increase the first index i.e pixels[1][1], I get a bus error 10. Any help would be appreciated. I've cut out some code to make it more readable but if you require all of it let me know! What the program is doing is reading a PPM image and displaying the information, the trouble i'm having is storing the pixels of the image.

#define MAX_HEIGHT 4
#define MAX_WIDTH 4

typedef struct Pixel{

  int red;
  int green;
  int blue;

}Pixel;

typedef struct PPM{

  char code[2];
  int width, height;
  int max;
  Pixel * pixels[MAX_HEIGHT][MAX_WIDTH];


}PPM;

struct PPM * getPPM(FILE * fd){

   PPM * image = NULL;

   image = malloc(sizeof(PPM));

   //have got all the other PPM info here ask if needed


   int i;
   int j;


   for(i = 0; i<MAX_HEIGHT-1; i++){
     for(j = 0; j<MAX_WIDTH-1; j++){
       //  struct Pixel newPPM_Pixel;
       if(fscanf(fd, "%d %d %d", &image->pixels[i][j]->red, &image->pixels[i][j]->green, &image->pixels[i][j]->blue) == 3){
       //rgb_array[i][j] = newPPM_Pixel;
       printf("/ %d / %d  / %d", image->pixels[i][j]->red, image->pixels[i][j]->green, image->pixels[i][j]->blue);
      }
    }
  }

 return image;
}

1 Answers1

0

Change line :

Pixel * pixels[MAX_HEIGHT][MAX_WIDTH];

to :

Pixel pixels[MAX_HEIGHT][MAX_WIDTH];    //without an asterisk

This is the way to declare a 2D array. If you want pixels to be a pointer, declare it like this :

Pixel **pixels;

and then dynamically allocate memory for it :

int i;
pixels = malloc (MAX_HEIGHT*sizeof(Pixel*));
if (pixels == NULL)
    printf ("Error allocating memory\n");
for (i = 0; i < MAX_HEIGHT; i++)
    pixels[i] = malloc(MAX_WIDTH*sizeof(Pixel));
    if (pixels[i] == NULL)
        printf ("Error allocating memory\n");

You can read more about 2D dynamic memory allocation here.

Marievi
  • 4,951
  • 1
  • 16
  • 33