-3

I have this code:

#include <stdio.h>
#include <stdlib.h>
int main() {
    int i,j,width,height,operatie;
    struct pixel {
       unsigned char r, g, b;
    } ;
    struct pixel **poza;
    scanf("%d",&operatie);
    scanf("%d",&width);
    scanf("%d",&height);
    poza = malloc ( height * width * sizeof(pixel));
    for (i=0 ; i<height ; i++ ) {
        for ( j=0 ; j<width ; j++ ) {
            scanf("%c",&(poza[i][j].r));
            scanf("%c",&(poza[i][j].g));
            scanf("%c",&(poza[i][j].b));
        }
    }
    for (i=0 ; i<height ; i++ ) {
        for ( j=0 ; j<width ; j++ ) {
            printf("%d ",(poza[i][j].r));
            printf("%d ",(poza[i][j].g));
            printf("%d ",(poza[i][j].b));
        }
        printf("\n");
    }

    return 0;
}

I want to know how I can use malloc, calloc and realloc on this. Please explain to me, if you can, how it works.

Jens
  • 69,818
  • 15
  • 125
  • 179
  • `poza = malloc ( height * width * sizeof(pixel));` ----> `poza = malloc ( height * width * sizeof(struct pixel));` – LPs Dec 02 '16 at 07:27

1 Answers1

1

Many issues there:

#include <stdio.h>
#include <stdlib.h>

struct pixel {
   int r, g, b;
} ;

int main( void )
{
    int i,j,width,height,operatie;

    struct pixel *poza;
    struct pixel *temp;

    scanf("%d",&operatie);
    scanf("%d",&width);
    scanf("%d",&height);

    poza = malloc ( height * width * sizeof(struct pixel));

    if (poza != NULL)
    {
        for (i=0 ; i<height ; i++ )
        {
            temp = &poza[i*height];

            for ( j=0 ; j<width ; j++ )
            {
                scanf("%d",&(temp[j].r));
                scanf("%d",&(temp[j].g));
                scanf("%d",&(temp[j].b));
            }
        }

        for (i=0 ; i<height ; i++ )
        {
            temp = &poza[i*height];

            for ( j=0 ; j<width ; j++ )
            {
                printf("%d ",(temp[j].r));
                printf("%d ",(temp[j].g));
                printf("%d ",(temp[j].b));
            }
            printf("\n");
        }
    }

    free(poza);

    return 0;
}
  1. pixel is a struct so sizeof(pixel) must be sizeof(struct pixel)
  2. I changed the format specifier of scanf to (and struct pixelr, g, b types) to ensure to store converted from ascii value. Using %c you are storing ascii values of input data and you have issues with '\n' chars.
  3. I changed the type of poza to use a simple pointer. Do not use pointer of pointers because in that way you'll fragment your memory.
  4. As you can see I used a temp variable to make the code more readable (my personal opinion). In the shown way you can point to the correct displacement of "rows" into your array and then loop through "cols".
LPs
  • 16,045
  • 8
  • 30
  • 61