Home > Software engineering >  In C, why can't I set a value of a element in a 2D array?
In C, why can't I set a value of a element in a 2D array?

Time:06-11

When I assign a pixel to a var why can I not assign it a value?

for (int i = 0; i < height; i  )
    {
        for (int j = 0; j < width; j  )
        {
        RGBTRIPLE pixel = image[i][j];
        double avgcolor = (pixel.rgbtBlue   pixel.rgbtGreen   pixel.rgbtRed) / 3.0;

        avgcolor = round(avgcolor);
        pixel.rgbtBlue = avgcolor; <-- fails
        pixel.rgbtRed = avgcolor; <-- fails
        pixel.rgbtGreen = avgcolor; <-- fails

        image[i][j].rgbtBlue = avgcolor; <-- works
        image[i][j].rgbRed = avgcolor; <-- works
        image[i][j].rgbtGreen = avgcolor; <-- works
    }
}
return;

CodePudding user response:

The following line makes a new copy of the object:

RGBTRIPLE pixel = image[i][j];

You need to maintain a reference to the original object, so you have to use a pointer type:

RGBTRIPLE *pixel = &image[i][j];

Now you can do:

pixel->rgbtBlue = avgcolor;
pixel->rgbtRed = avgcolor;
pixel->rgbtGreen = avgcolor;

CodePudding user response:

The = operator will copy your struct. I.e., after calling RGBTRIPLE pixel = image[i][j];, pixel is a copy of image[i][j], so updating it does not update the original image[i][j].

One way around this is to use a pointer:

GBTRIPLE* pixel = &image[i][j];
double avgcolor = (pixel.rgbtBlue   pixel.rgbtGreen   pixel.rgbtRed) / 3.0;

avgcolor = round(avgcolor);
pixel->rgbtBlue = avgcolor;
pixel->rgbtRed = avgcolor;
pixel->rgbtGreen = avgcolor;

CodePudding user response:

RGBTRIPLE pixel = image[i][j];

I think it does work.

But I think you are misunderstanding the relationship between the left-hand side (lhs) and the right-hand side (rhs) of the assignment operator.

In this case the assignment works but does nothing to change the values in the array image.

image[i][j] being on the right is evaluated as a read-only value, copying over the contents of pixel each time the j loop iterates.

I believe you solved this on your own, so I will leave it at that. However I think you could collapse this into a single loop, and a single assignment within it.

  •  Tags:  
  • c
  • Related