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

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

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

  1. ส่งสมาชิกแต่ละตัว (Passing individual members) - หัวข้อนี้
  2. ส่ง Structure ทั้งหมด
  3. ส่งที่อยู่ของ Structure

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

  • ส่งสมาชิกแต่ละตัวของ structure ไปใน function call พร้อมกับ subscript (ดัชนี)
  • ฟังก์ชันรับค่าในตัวแปรธรรมดา (ordinary variables) ไม่ใช่ structure
  • เหมาะสำหรับส่งข้อมูลไม่มาก หรือต้องการประมวลผลเฉพาะบางสมาชิก

ตัวอย่างโปรแกรมที่ 1: ส่งสมาชิก day, month, year แยกกัน

#include <stdio.h>
struct date {
    int day;
    int mon;
    int yr;
};
void display(int a, int b, int c); // รับค่าเป็นตัวแปร int ธรรมดา 3 ตัว

int main() {
    struct date d = {02, 01, 2010};
    display(d.day, d.mon, d.yr); // ส่งสมาชิกแต่ละตัว
    return 0;
}
void display(int a, int b, int c) {
    printf("วัน = %d\\n", a);
    printf("เดือน = %d\\n", b);
    printf("ปี = %d\\n", c);
}

ผลลัพธ์

วัน = 2
เดือน = 1
ปี = 2010

ตัวอย่างโปรแกรมที่ 2: ส่งข้อมูลนักศึกษาแยกสมาชิก

#include <stdio.h>
#include <string.h>
struct student {
    int id;
    char name[20];
    float percentage;
    char temp;
};
struct student record; // Global declaration

void structure_demo(int id, char name[], float percentage);

int main() {
    record.id = 1;
    strcpy(record.name, "Raju");
    record.percentage = 86.5;
    structure_demo(record.id, record.name, record.percentage);
    return 0;
}
void structure_demo(int id, char name[], float percentage) {
    printf("รหัส: %d\\n", id);
    printf("ชื่อ: %s\\n", name);
    printf("เปอร์เซ็นต์: %.2f\\n", percentage);
}

ผลลัพธ์

รหัส: 1
ชื่อ: Raju
เปอร์เซ็นต์: 86.50

สรุปการเปรียบเทียบ 3 วิธี

วิธีการส่งการรับในฟังก์ชันข้อดีข้อเสีย
สมาชิกแยกตัวส่งค่าแต่ละ memberตัวแปรธรรมดาเข้าใจง่าย เหมาะข้อมูลน้อยโค้ดยาว ถ้ามี member เยอะ
Structure ทั้งตัวส่ง structure variablestructure variable (copy)โค้ดสั้น อ่านง่ายใช้หน่วยความจำมาก (copy)
ที่อยู่ (Pointer)ส่ง &struct_varpointer to structureประหยัดหน่วยความจำ เร็ว สามารถแก้ไขต้นฉบับได้ซับซ้อนกว่าเล็กน้อย