Search code examples
arrayscstructinitialization

initializing a 2 dimensional array of struct to zero (set the image to all black) in C


I want to pass an image file to a function and make it all black.

Here is how I do it:

typedef struct
{
    BYTE  rgbtBlue;
    BYTE  rgbtGreen;
    BYTE  rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;

void black(int height, int width, RGBTRIPLE image[height][width])
{
    RGBTRIPLE black_image[height][width];
    
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            black_image[i][j] = {0}; 
        }
    }
    
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            image[i][j] = black_image[i][j]; 
        }
    }
}

However, I am getting the same error message :

expected expression before '{' token black_image[i][j] = {0};
                                                         ^      

Notice the pointer pointing to the curly bracket.

What have I done wrong here? Please help.


Solution

  • {0} is a syntax used in initializations, when objects are defined. It does not form an expression that can be used in assignment statements.

    For this, you can use a compound literal:

    black_image[i][j] = (RGBTRIPLE) { 0, 0, 0 };
    

    (This would also work as (RGBTRIPLE) {0}, but listing all three components shows the intent more clearly and may avoid a compiler warning.)

    Since you are just using this to set image to black, you can eliminate black_image and the loop that initializes it and just set image directly to zero.