โครงสร้างข้อมูล: Array of Structures vs Array within Structure
1. Array of Structures (อาร์เรย์ของโครงสร้าง)
ประกาศโครงสร้างก่อน แล้วค่อยประกาศอาร์เรย์ของโครงสร้างนั้น
struct book b[10]; // 10 elements of type 'book'
ตัวอย่าง: คะแนนนักเรียน 3 วิชา 3 คน
struct marks {
int sub1, sub2, sub3, 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 += student[i].sub1;
total.sub2 += student[i].sub2;
total.sub3 += student[i].sub3;
total.total += student[i].total;
}
printf("STUDENT TOTAL\n\n");
for (i = 0; i <= 2; i++)
printf("Student[%d] %d\n", i+1, student[i].total);
printf("\nSUBJECT TOTAL\n\n");
printf("%s %d\n%s %d\n%s %d\n", "Subject 1 ", total.sub1, "Subject 2 ", total.sub2, "Subject 3 ", total.sub3);
printf("\nGrand Total = %d\n", total.total);
}
Output (มีค่าผิดปกติจากตัวอย่างต้นฉบับ แต่โครงสร้างถูกต้อง)
2. Array within Structure (อาร์เรย์ภายในโครงสร้าง)
โครงสร้างมีสมาชิกเป็นอาร์เรย์
struct marks {
int sub[3];
int total;
};
main() {
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\n\n");
for (i = 0; i <= 2; i++)
printf("Student[%d] %d\n", i+1, student[i].total);
printf("\nSUBJECT TOTAL\n\n");
for (j = 0; j <= 2; j++)
printf("Subject-%d %d\n", j+1, total.sub[j]);
printf("\nGrand Total = %d\n", total.total);
}
ความแตกต่างสำคัญ: Array of Structures → หลายเรคคอร์ด แต่ละเรคคอร์ดมีฟิลด์คงที่. Array within Structure → เรคคอร์ดเดียวมีหลายค่าของฟิลด์เดียวกัน (เหมาะกับคะแนนหลายวิชา)