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

การส่งที่อยู่ของ Structure เป็นอาร์กิวเมนต์ให้ฟังก์ชันในภาษา C

วิธีการส่งข้อมูล Structure ให้ฟังก์ชัน (3 วิธี)

  1. ส่งสมาชิกแต่ละตัวเป็นอาร์กิวเมนต์ (Passing individual members)
  2. ส่ง Structure ทั้งหมดเป็นอาร์กิวเมนต์ (Passing entire structure)
  3. ส่งที่อยู่ของ Structure เป็นอาร์กิวเมนต์ (Passing address of structure) - หัวข้อนี้

หลักการทำงาน

  • ส่งที่อยู่ (address) ของตัวแปร structure ไปให้ฟังก์ชัน
  • ฟังก์ชันรับค่าในพารามิเตอร์ที่เป็น pointer to structure
  • ใช้ arrow operator (->) เพื่อเข้าถึงสมาชิกผ่าน pointer

ข้อดี

  • ไม่เสียหน่วยความจำเพราะไม่ต้องสร้างสำเนา (copy) ของ structure
  • ไม่ต้อง return ค่ากลับ เพราะฟังก์ชันสามารถเข้าถึงและแก้ไข structure ต้นฉบับได้โดยตรง
  • เหมาะสำหรับ structure ขนาดใหญ่

ตัวอย่างโปรแกรมที่ 1: ส่งที่อยู่ Structure ให้ฟังก์ชัน display

#include <stdio.h>
struct date {
    int day;
    char month[10];
    int year;
};
void display(struct date *p); // prototype

int main() {
    struct date d;
    printf("ป้อนวัน เดือน ปี: ");
    scanf("%d%s%d", &d.day, d.month, &d.year);
    display(&d); // ส่งที่อยู่ของ d
    return 0;
}
void display(struct date *p) {
    printf("วัน=%d\\n", p->day);
    printf("เดือน=%s\\n", p->month);
    printf("ปี=%d\\n", p->year);
}

ผลลัพธ์

ป้อนวัน เดือน ปี: 20 MAR 2021
วัน=20
เดือน=MAR
ปี=2021

ตัวอย่างโปรแกรมที่ 2: จัดการข้อมูลนักศึกษาแบบ Array of Structures

#include <stdio.h>
struct student {
    char Name[100];
    int Age;
    float Level;
    char Grade[50];
    char temp;
} s[5];

void show(struct student *p) {
    int i;
    for (i = 0; i < 2; i++) {
        printf("ชื่อนักศึกษา %d: %s\\n", i+1, p->Name);
        printf("อายุ %d: %d\\n", i+1, p->Age);
        printf("ระดับ %d: %f\\n", i+1, p->Level);
        printf("เกรด %d: %s\\n", i+1, p->Grade);
        p++; // ขยับ pointer ไป element ถัดไป
    }
}

int main() {
    int i;
    struct student *p;
    for (i = 0; i < 2; i++) {
        printf("ป้อนชื่อนักศึกษา %d: ", i+1);
        gets(s[i].Name); // หมายเหตุ: gets ไม่ปลอดภัย ควรใช้ fgets
        printf("ป้อนอายุ %d: ", i+1);
        scanf("%d", &s[i].Age);
        printf("ป้อนระดับ %d: ", i+1);
        scanf("%f", &s[i].Level);
        scanf("%c", &s[i].temp); // ล้าง buffer
        printf("ป้อนเกรด %d: ", i+1);
        gets(s[i].Grade);
    }
    p = &s[0];
    show(&s[0]); // หรือ show(p);
    return 0;
}

ผลลัพธ์ตัวอย่าง

ป้อนชื่อนักศึกษา 1: Lucky
ป้อนอายุ 1: 27
ป้อนระดับ 1: 2
ป้อนเกรด 1: A
ป้อนชื่อนักศึกษา 2: Pinky
ป้อนอายุ 2: 29
ป้อนระดับ 2: 1
ป้อนเกรด 2: B
ชื่อนักศึกษา 1: Lucky
อายุ 1: 27
ระดับ 1: 2.000000
เกรด 1: A
ชื่อนักศึกษา 2: Pinky
อายุ 2: 29
ระดับ 2: 1.000000
เกรด 2: B