Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

Array of Structures (อาร์เรย์ของโครงสร้าง) ในภาษา C


Array of Structures คืออะไร?

การประกาศ Array ที่แต่ละ Element เป็น Structure - เป็นการใช้งาน Structure ที่พบบ่อยที่สุด

วิธีการประกาศ

  1. กำหนด Structure ก่อน
  2. ประกาศ Array ของ Structure นั้น
struct book {
    int id;
    char title[50];
    float price;
};

struct book library[100]; // Array 100 elements ของ struct book

ตัวอย่างโปรแกรม: จัดการข้อมูลนักเรียน

#include <stdio.h>
#include <string.h>

struct student {
    int id;
    char name[30];
    float percentage;
};

int main() {
    int i;
    struct student record[3]; // Array 3 students
    
    // Student 1
    record[0].id = 1;
    strcpy(record[0].name, "Bhanu");
    record[0].percentage = 86.5;
    
    // Student 2
    record[1].id = 2;
    strcpy(record[1].name, "Priya");
    record[1].percentage = 90.5;
    
    // Student 3
    record[2].id = 3;
    strcpy(record[2].name, "Hari");
    record[2].percentage = 81.5;
    
    // แสดงผล
    for (i = 0; i < 3; i++) {
        printf("Record of STUDENT %d:\n", i+1);
        printf("  ID: %d\n", record[i].id);
        printf("  Name: %s\n", record[i].name);
        printf("  Percentage: %.2f%%\n\n", record[i].percentage);
    }
    
    return 0;
}

ผลลัพธ์:


Record of STUDENT 1:
  ID: 1
  Name: Bhanu
  Percentage: 86.50%

Record of STUDENT 2:
  ID: 2
  Name: Priya
  Percentage: 90.50%

Record of STUDENT 3:
  ID: 3
  Name: Hari
  Percentage: 81.50%

การเข้าถึงสมาชิก

รูปแบบคำอธิบาย
record[i].memberเข้าถึงสมาชิกของ element ที่ i
(record+i)->memberใช้ Pointer arithmetic (เทียบเท่าข้างบน)
record[i].nameเข้าถึง string (char array)

การประกาศแบบ Dynamic (Runtime)


int n;
printf("Enter number of students: ");
scanf("%d", &n);

struct student *records = malloc(n * sizeof(struct student));
// ใช้ records[i] เหมือน array ปกติ
free(records); // จำเป็นต้อง free เมื่อไม่ใช้แล้ว

การประยุกต์ใช้

  • ฐานข้อมูลนักเรียน/พนักงาน/สินค้า
  • Game: Array ของ Enemies, Items, Players
  • ระบบจัดการข้อมูลทุกประเภท