C 程序区分结构数组和结构中的数组
在 C 编程语言中,对结构最常见的用法是结构数组。
要声明一个结构数组,必须先定义结构,然后定义该类型的数组变量。
例如:
struct book b[10];//10 elements in an array of structures of type ‘book’
示例
以下是结构数组的 C 程序 −
struct marks{ int sub1; int sub2; int sub3; int total; }; main(){ int i; struct marks student[3] = {{20,17,11,10}, {175,23,169,10}, {27,56,27,01}}; struct marks total; for(i = 0; i <= 2; i++){ student[i].total = student[i].sub1 + student[i].sub2 + student[i].sub3; total.sub1 = total.sub1 + student[i].sub1; total.sub2 = total.sub2 + student[i].sub2; total.sub3 = total.sub3 + student[i].sub3; total.total = total.total + student[i].total; } printf(" STUDENT TOTAL
"); for(i = 0; i <= 2; i++) printf("Student[%d] %d
", i+1,student[i].total); printf("
SUBJECT TOTAL
"); printf("%s %d
%s %d
%s %d
", "Subject 1 ", total.sub1, "Subject 2 ", total.sub2, "Subject 3 ", total.sub3); printf("
Grand Total = %d
", total.total); }
输出
执行以上程序时,会产生以下输出 −
STUDENT TOTAL Student[1] 48 Student[2] 367 Student[3] 110 SUBJECT TOTAL Subject 1 4200462 Subject 2 96 Subject 3 223 Grand Total = 525
示例
以下是结构中的数组的 C 程序 −
main(){ struct marks{ int sub[3]; int total; }; struct marks student[3] = {145,50,11,10,175,50,19,10,20,30,25,10}; struct marks total; int i,j; for(i = 0; i <= 2; i++){ for(j = 0; j <= 2; j++){ student[i].total += student[i].sub[j]; total.sub[j] += student[i].sub[j]; } total.total += student[i].total; } printf("STUDENT TOTAL
"); for(i = 0; i <= 2; i++) printf("Student[%d] %d
", i+1, student[i].total); printf("
SUBJECT TOTAL
"); for(j = 0; j <= 2; j++) printf("Subject-%d %d
", j+1, total.sub[j]); printf("
Grand Total = %d
", total.total); }
输出
执行以上程序时,会产生以下输出 −
STUDENT TOTAL Student[1] 216 Student[2] 254 Student[3] 85 SUBJECT TOTAL Subject-1 4200548 Subject-2 130 Subject-3 71 Grand Total = 555
广告