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

Pass by Reference ในภาษา C

ความหมาย

Pass by Reference ใน C ทำได้โดยการส่งที่อยู่ (address) ของตัวแปรเป็นอาร์กิวเมนต์ ฟังก์ชันจะรับค่าในพารามิเตอร์ที่เป็น pointer จึงสามารถแก้ไขค่าตัวแปรต้นฉบับได้

อัลกอริทึมการ Swap แบบ Pass by Reference

START
Step 1: ประกาศฟังก์ชัน swap รับ pointer parameters
Step 2: ประกาศตัวแปร a, b
Step 3: รับค่า a, b จากผู้ใช้
Step 4: เรียก swap(&a, &b) ส่งที่อยู่
Step 5: พิมพ์ค่า a, b หลัง swap
Step 6: ฟังก์ชัน swap:
    i.  ประกาศ temp
    ii. temp = *a
    iii. *a = *b
    iv. *b = temp
STOP

ตัวอย่างโปรแกรมที่ 1: Swap สองตัวเลข

#include <stdio.h>
void swap(int *a, int *b);

int main() {
    int a, b;
    printf("ป้อนตัวเลข 2 ตัว: ");
    scanf("%d%d", &a, &b);
    printf("ก่อน swap: a=%d, b=%d\\n", a, b);
    swap(&a, &b); // ส่งที่อยู่
    printf("หลัง swap: a=%d, b=%d\\n", a, b);
    return 0;
}
void swap(int *a, int *b) {
    int t = *a;
    *a = *b;
    *b = t;
}

ผลลัพธ์

ป้อนตัวเลข 2 ตัว: 10 20
ก่อน swap: a=10, b=20
หลัง swap: a=20, b=10

ตัวอย่างโปรแกรมที่ 2: เพิ่มค่าด้วย Pass by Reference

#include <stdio.h>
void inc(int *num) {
    *num = *num + 5; // เพิ่มค่าที่ address จริง
}
int main() {
    int a = 20, b = 30, c = 40;
    inc(&a);
    inc(&b);
    inc(&c);
    printf("ค่า a: %d\\n", a);
    printf("ค่า b: %d\\n", b);
    printf("ค่า c: %d\\n", c);
    return 0;
}

ผลลัพธ์

ค่า a: 25
ค่า b: 35
ค่า c: 45

Pass by Reference vs Pass by Value

คุณสมบัติPass by ValuePass by Reference
ส่งอะไรค่า (value)ที่อยู่ (address)
พารามิเตอร์ในฟังก์ชันตัวแปรธรรมดาPointer
ส่งผลต่อตัวแปรต้นฉบับไม่ส่งผลส่งผลโดยตรง
หน่วยความจำสร้าง copyไม่สร้าง copy
ใช้เมื่อไม่ต้องการแก้ไขต้นฉบับต้องการแก้ไขต้นฉบับ หรือ structure ใหญ่

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

  • ฟังก์ชันที่ต้อง return หลายค่า (ผ่าน pointer parameters)
  • ส่ง structure/array ใหญ่ เพื่อประหยัดหน่วยความจำ
  • Dynamic memory allocation (malloc คืน pointer)
  • Linked list, tree operations