Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

c initialize array and structs at the same time

I'm trying to initialize both an array and the structs that it contains

#include <stdio.h>
#include <math.h>

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

void edges(int height, int width, RGBTRIPLE image[height][width]);

int main()
{
    int height = 3;
    int width = 3;
    RGBTRIPLE image[height][width] = {
        {{0, 10, 25}, {0, 10, 30}, {40, 60, 80}},
        {{20, 30, 90}, {30, 40, 100}, {80, 70, 90}},
        {{20, 20, 40}, {30, 10, 30}, {50, 40, 10}}
    };
    return 0;
}

I'm not sure whether this initialization can happen at the same time or if I must initialize first all the structs before inserting them into the array.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can give initial values for the elements in an array, including members of structures in the array, when defining an array.

The C standard says a thing being initialized shall not have variable length array type (C 2018 6.7.9 3). Your array has variable length array type because height and width are variables, not constants as C defines them. To fix that, you can use #define directives or enum declarations to define height and width.

If you do need a variable length array or a dynamically allocated array, you can give values to its elements using assignment statements, including assignments of whole structures using a compound literal for each structure, as in:

image[i][j] = (RGBTRIPLE) { 0, 10, 25 };

However, the C standard does not provide any way to give initial values to a variable length array or dynamically allocated array during its creation. With optimization, assigning values immediately after creating an array will likely be equivalent to initializing them during creation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...