1. 程式人生 > >結構體初始化方式

結構體初始化方式

   幾種結構體的初始化方式.

?
12345678910111213141516171819202122232425262728293031323334353637383940struct 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",};

如果想初始化結構體陣列,可採用 {{ }, { }, { }} 方式,如

?
12345678910111213struct student_st stus[2] = {{.c = 'B',.score = 80,/*也可以只初始化部分成員*/},{.c = 'C',.score = 60,.name = "Jack"},};