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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP