On the initialization of structure in C language

  • 2020-04-01 23:38:12
  • OfStack

The code book recommends initialization at the time of variable definition, but many people, especially newcomers, do not always initialize structures or arrays of structures, or do not know how to initialize them.
1. Initialization

typedef struct _TEST_T {
        int i;
        char c[10];
}TEST_T;
TEST_T gst  = {1,  " 12345 " };//I can initialize, set I to 1 and s to a string.
TEST_T gst  = {1};//When the number of initializations is less than the actual number, only the preceding member is initialized.
TEST_Tgst  = {.c= " 12345 " };//A selected initialization member.

2. Compound literals.
GST (TEST_T) = {122, "1256"}; // this is an assignment statement and can also be used as an initialization. It can appear anywhere in the program.
Of course, you can also use the compound literal to initialize:
GST (TEST_T) = {. I = 122. C = "123"};
3. Structure array
Can be enclosed in multiple braces:
TEST_T GST [10] = {{}, {}, {}, {}}
You can also initialize one of the elements:
TEST_T GST [10] ={[2]={}, [3]={}}
You can also use the compound literal:
TEST_T GST [10] ={[2]. I =0, [3]. I ={}}
Why initialize:
1. Initialization of local variables can prevent the harm caused by random values.
2. Initializing a global variable tells the compiler that it is a definition, not a declaration. If two cs have the same global variable definition and are not initialized, the compiler will consider the second to be a declaration rather than a definition.

Related articles: