0

I'm trying to read a matrix of pixels from stdin and just print it. I'm using a structure for the pixels, defined like this:

    typedef struct pixel {
        int R, G, B;
    } RGB;

Allocate space for it

    matrixPixels = (RGB**)calloc(height,sizeof(int*));
    for(row = 0; row < height; row++)
       matrixPixels[row] = (RGB*)calloc(width,sizeof(int));

In main I'm reading the width and height of the matrix and assign values to each pixel like this:

    for(row = 0; row < height; row++) 
        for(column = 0; column < width; column++) {
            scanf("%d %d %d ", &matrixPixels[row][column].R, &matrixPixels[row][column].G, &matrixPixels[row][column].B);

Now, my problem would be that when I'm trying to print the matrix using

    for(row = 0; row < height; row++)
       for(column = 0; column < width; column++) 
          printf("%d %d %d", matrixPixels[row][column].R, matrixPixels[row][column].G, matrixPixels[row][column].B);

Some values are not what they're supposed to be... As an example, if the width and height are 3 and 2 and I'm reading 87 88 255 40 60 50 70 80 90 55 56 57 66 67 68 77 78 79, when I'm printing it, instead of the value 90 I have 55 for some unknown reason and I can't figure out why...

Crouze
  • 13
  • 3
  • 3
    `matrixPixels = (RGB**)calloc(height,sizeof(int*));` you'll have to explain *why* you're allocating the wrong size for no apparent reason here (and in the other `calloc()`). – EOF Dec 09 '16 at 21:02
  • Oh, that was it xD thank youuuu – Crouze Dec 09 '16 at 21:05
  • 1
    `sizeof(int*)` --> `sizeof(RGB*)`, `sizeof(int)` --> `sizeof(RGB)` – BLUEPIXY Dec 09 '16 at 21:05
  • @BLUEPIXY: Do you ever get tired of this? – EOF Dec 09 '16 at 21:06
  • 1
    You're asking for trouble here.The actual problem is sizeof int vs sizeof struct pixel. But if you manipulate images as flat arrays of the channel type life will be a lot easier. – Malcolm McLean Dec 09 '16 at 21:14
  • Do *NOT* cast the return of `malloc` (or `calloc`). See: [**Do I cast the result of malloc?**](http://stackoverflow.com/q/605845/995714) for thorough explanation. – David C. Rankin Dec 10 '16 at 04:35

1 Answers1

1

You had used wrong size to allocate structures:

matrixPixels = calloc(height,sizeof(RGB*));
    for(row = 0; row < height; row++)
       matrixPixels[row] = calloc(width,sizeof(RGB));

And it's really good habit to not cast any allocating functions.

koper89
  • 645
  • 3
  • 9