结构体初始化方式

   几种结构体的初始化方式.


?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 
struct student
{
     char c;
     int score;
     const char *name;
};


     //方式 1: 按照成员声明的顺序初始化
     struct student_st s1 = { 'C' , 100 , "Tom" };
     show_student(&s1);
 
     // 方式 2: 指定初始化,成员顺序可以不定,Linux 内核多采用此方式 (C风格)
     struct student_st s2 =
     {
         .name = "Tom" ,
         .c = 'C' ,
         .score = 100 ,
     };
     show_student(&s2);
 
     // 方式 3: 指定初始化,成员顺序可以不定 (C++风格)
     struct student_st s3 =
     {
         c: 'C' ,
         score: 100 ,
         name: "Tom" ,
     };
 

 

如果想初始化结构体数组,可采用 {{ }, { }, { }} 方式,如

?
1
2
3
4
5
6
7
8
9
10
11
12
13
struct student_st stus[ 2 ] =
{
     {
         .c = 'B' ,
         .score = 80 ,
         /*也可以只初始化部分成员*/
     },
     {
         .c = 'C' ,
         .score = 60 ,
         .name = "Jack"
     },
};

猜你喜欢

转载自blog.csdn.net/qq_17308321/article/details/79819366