- C语言结构体初始化的三种方法:原文链接http://www.2cto.com/kf/201503/386575.html
-
12345678910111213141516171819202122232425262728293031323334353637383940
#include <stdio.h>struct student_st{charc;intscore;constchar*name;};staticvoidshow_student(struct student_st *stu){printf("c = %c, score = %d, name = %s\n", stu->c, stu->score, stu->name);}intmain(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);return0;}</stdio.h>运行结果:
如果想初始化结构体数组,可采用 {{ }, { }, { }} 方式,如
12345678910111213struct student_st stus[2] ={{.c ='D',.score =94,/*也可以只初始化部分成员*/},{.c ='D',.score =94,.name ="Xxx"},};