Nested Structure คืออะไร?
Structure ภายใน Structure** (Structure within Structure) เรียกว่า **Nested Structure** ใช้จัดกลุ่มข้อมูลที่เกี่ยวข้องกัน
ตัวอย่างเปรียบเทียบ
ไม่ใช้ Nested (Flat)
struct emp {
int eno;
char ename[30];
float sal;
float da; // Allowance
float hra; // Allowance
float ea; // Allowance
} e;
ใช้ Nested Structure (จัดกลุ่ม Allowances)
struct emp {
int eno;
char ename[30];
float sal;
struct allowance { // Nested structure
float da;
float hra;
float ea;
} a; // ตัวแปร nested structure
} e;
การเข้าถึงสมาชิก Nested
ใช้ **Dot Operator (.)** ต่อเนื่องจากนอกสุดเข้าสู่วในสุด
e.a.da // eno → allowance → da
e.a.hra
e.a.ea
ตัวอย่างโปรแกรมสมบูรณ์
#include <stdio.h>
struct Person {
char Name[50];
int Age;
char Gender;
struct Address { // Nested Structure
char City[100];
char State[100];
int Zipcode;
} addr; // ตัวแปร nested
} person[2];
int main() {
for (int i = 0; i < 2; i++) {
printf("Person %d:\n", i+1);
printf(" Name: "); scanf("%49s", person[i].Name);
printf(" Age: "); scanf("%d", &person[i].Age);
printf(" Gender (M/F): "); scanf(" %c", &person[i].Gender);
printf(" City: "); scanf("%99s", person[i].addr.City);
printf(" State: "); scanf("%99s", person[i].addr.State);
printf(" Zip: "); scanf("%d", &person[i].addr.Zipcode);
}
printf("\n--- Data Entered ---\n");
for (int i = 0; i < 2; i++) {
printf("Person %d: %s, Age %d, %c, %s, %s, %d\n",
i+1, person[i].Name, person[i].Age, person[i].Gender,
person[i].addr.City, person[i].addr.State, person[i].addr.Zipcode);
}
return 0;
}
ผลลัพธ์ตัวอย่าง:
Person 1:
Name: John
Age: 30
Gender (M/F): M
City: New York
State: NY
Zip: 10001
Person 2:
Name: Jane
Age: 25
Gender (M/F): F
City: Los Angeles
State: CA
Zip: 90001
--- Data Entered ---
Person 1: John, Age 30, M, New York, NY, 10001
Person 2: Jane, Age 25, F, Los Angeles, CA, 90001
ข้อดีของ Nested Structure
- จัดระเบียบข้อมูลที่เกี่ยวข้อง (Group related data)
- อ่านโค้ดเข้าใจง่ายขึ้น (Readability)
- ลดการซ้ำของชื่อ (Namespace management)
- สะดวกในการ Copy/Assign ทั้งกลุ่ม
ข้อควรระวัง
- ไม่ควรซ้อนลึกเกินไป (Max 2-3 ระดับ)
- ขนาด Struct = ผลรวมขนาดสมาชิกทั้งหมด (รวม Nested)
- Padding/Alignment ยังคงใช้งานตามปกติ