Invalid argument of type '-> (is "color")

I have the following source code that allocates space for an image, its pixels, and reads in the pixel values.

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



typedef struct color
{
    int r,g,b;
}color;


typedef struct image
{
    int width, height;
    color *pixels;
}image;

image* CreateImage(int width, int height)
{

    imagem *im=NULL;
    im=(image*)malloc(sizeof(image));
    im->height=height;
    im->width=width;
    im->pixels=(color*)malloc(width*height*sizeof(color));

    int i;

    //error starts here
    for (i=0; i<width*height;i++)
    {
        scanf('%d', &im->pixels[i]->r);
        scanf('%d', &im->pixels[i]->g);
        scanf('%d', &im->pixels[i]->b);

    }


return im;
}

      

The problem starts in the part of the code where the image pixels are read. When I compile it the error is "invalid type argument" -> (there is "color")

I know we should use '->' if the left operand is a pointer. Here the image and pixels are pointers, so why can't I use im-> pixels [i] → r for example? how can i solve this problem?

+3


source to share


3 answers


scanf("%d", &im->pixels[i].r);

pixels[i] = *(pixels + i); /* [] has already dereferenced */

      



As shown above, you need to have double quotes in scanf () instead of single quotes

+1


source


pixels

is indeed a pointer, but your use []

has already dereferenced it. Do you want to:

 &im->pixels[i].r

      



Note that your call scanf

must contain a string as the first parameter, not a multi-character literal - use double quotes there.

+5


source


You can use the operator ->

if you really want:

( im->pixels+i )->r = 123 ;

      

This is identical

im->pixels[i].r = 123 ;

      

+1


source







All Articles