วิธีการส่งข้อมูล Structure ให้ฟังก์ชัน (3 วิธี)
- ส่งสมาชิกแต่ละตัว (Passing individual members) - หัวข้อนี้
- ส่ง Structure ทั้งหมด
- ส่งที่อยู่ของ 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 variable | structure variable (copy) | โค้ดสั้น อ่านง่าย | ใช้หน่วยความจำมาก (copy) |
| ที่อยู่ (Pointer) | ส่ง &struct_var | pointer to structure | ประหยัดหน่วยความจำ เร็ว สามารถแก้ไขต้นฉบับได้ | ซับซ้อนกว่าเล็กน้อย |