C語言結構體初始化的三種方法


直接上示例

 

?
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
#include <stdio.h>
 
struct student_st
{
     char c;
     int score;
     const char *name;
};
 
static void show_student(struct student_st *stu)
{
     printf( "c = %c, score = %d, name = %s\n" , stu->c, stu->score, stu->name);
}
 
int main( void )
{
     // method 1: 按照成員聲明的順序初始化
     struct student_st s1 = { 'A' , 91 , "Alan" };
     show_student(&s1);
 
     // method 2: 指定初始化,成員順序可以不定,Linux 內核多采用此方式
     struct student_st s2 =
     {
         .name = "YunYun" ,
         .c = 'B' ,
         .score = 92 ,
     };
     show_student(&s2);
 
     // method 3: 指定初始化,成員順序可以不定
     struct student_st s3 =
     {
         c: 'C' ,
         score: 93 ,
         name: "Wood" ,
     };
     show_student(&s3);
     
     return 0 ;
}</stdio.h>

 

運行結果

加載中...

 

如果想初始化結構體數組,可采用 {{ }, { }, { }} 方式,如

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM