1 struct Student //聲明Student類型結構體變量 2 { 3 char name[20]; 4 int score[5]; 5 }; 6 typedef struct Student Stu; 7 8 void main() 9 { 10 11 Stu stu[3]; 定義Student類型變量數組 12 int i,j; 13 for(i=0;i<3;i++) //輸入學生姓名和成績 14 { 15 printf("please input student[%d]'s name and scores:\n",i+1); 16 printf("Name:");scanf("%s",stu[i].name); 17 printf("\nScores:"); 18 for(j=0;j<4;j++) 19 { 20 scanf("%d",&stu[i].score[j]);} 21 stu[i].score[j]=0; 22 } 23 void aver(Stu s[],int n); 24 aver(stu,3); //求平均分 25 void fail(Stu s[],int n); 26 fail(stu,3); //打印不及格成績同學成績 27 } 28 void aver(Stu s[],int n) 29 { 30 int i,j; 31 float sum; 32 for(i=0;i<n;i++) 33 { 34 for(j=0,sum=0.0;j<4;j++) 35 { 36 sum=sum+s[i].score[j]; 37 } 38 s[i].score[j]=sum/j; 39 } 40 printf("average scores:\n"); 41 for(i=0;i<n;i++) 42 { 43 printf("\n%s :%.1d",s[i].name,s[i].score[4]); 44 } 45 printf("\n"); 46 } 47 void fail(Stu s[],int n) 48 { 49 int i,j; 50 for(i=0;i<n;i++) 51 { 52 for(j=0;j<4;j++) 53 { 54 if(s[i].score[j]<60) 55 { 56 printf("\n%s failed:",s[i].name); 57 printf("\nScores:"); 58 for(j=0;j<4;j++) 59 printf("%d\t",s[i].score[j]); 60 break; 61 } 62 } 63 } 64 }
結構體類型和int,char,數組等基本類型一樣,也是一種C語言數據類型,只不過這是一種自定義數據類型,我們可以根據需求由各種基本數據類型構造。
使用結構體變量時遵循變量使用的一般規則。一般把結構體類型聲明放到代碼的最前面,這一可以使其使用范圍為整個程序文件;也可以放在頭文件里。