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

การส่งที่อยู่ของ Structure เป็น Argument ให้ Function ในภาษา C

การส่งที่อยู่ (Address) ของ Structure ให้ฟังก์ชัน เรียกว่า Pass by Reference หรือ Call by Address

หลักการ

  • ส่งที่อยู่ของ Struct ด้วย &struct_var
  • รับในฟังก์ชันด้วย Pointer to Struct: struct tagname *ptr
  • เข้าถึงสมาชิกด้วย Arrow operator ->

ข้อดี

  1. ประหยัดหน่วยความจำ - ไม่ต้องสร้าง Copy ของ Struct ทั้งชุด
  2. แก้ไขค่าเดิมได้ - ฟังก์ชันเข้าถึง Struct ตัวจริง ส่งค่ากลับไม่จำเป็น
  3. เร็วกว่า - โดยเฉพาะ Struct ขนาดใหญ่

ตัวอย่างโปรแกรม

#include <stdio.h>

struct date {
    int day;
    int mon;
    int yr;
};

// ฟังก์ชันรับ pointer to struct date
void display(struct date *dt) {
    printf("Day = %d\n", dt->day);
    printf("Month = %d\n", dt->mon);
    printf("Year = %d\n", dt->yr);
}

int main() {
    struct date d = {2, 1, 2010};  // 2 Jan 2010
    display(&d);  // ส่งที่อยู่ของ d
    return 0;
}

ผลลัพธ์

Day = 2
Month = 1
Year = 2010

เปรียบเทียบ: Pass by Value vs Pass by Reference

ลักษณะPass by ValuePass by Reference (Address)
การส่งส่งค่าทั้ง Structส่งที่อยู่ &struct
หน่วยความจำCopy ใหม่ทั้งชุดใช้ Struct เดียวกัน
การแก้ไขค่าไม่ส่งผลต่อตัวเดิมแก้ไขตัวเดิมได้
ความเร็วช้ากว่า (Struct ใหญ่)เร็วกว่า