ความหมาย
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 Value | Pass by Reference |
|---|---|---|
| ส่งอะไร | ค่า (value) | ที่อยู่ (address) |
| พารามิเตอร์ในฟังก์ชัน | ตัวแปรธรรมดา | Pointer |
| ส่งผลต่อตัวแปรต้นฉบับ | ไม่ส่งผล | ส่งผลโดยตรง |
| หน่วยความจำ | สร้าง copy | ไม่สร้าง copy |
| ใช้เมื่อ | ไม่ต้องการแก้ไขต้นฉบับ | ต้องการแก้ไขต้นฉบับ หรือ structure ใหญ่ |
การประยุกต์ใช้จริง
- ฟังก์ชันที่ต้อง return หลายค่า (ผ่าน pointer parameters)
- ส่ง structure/array ใหญ่ เพื่อประหยัดหน่วยความจำ
- Dynamic memory allocation (malloc คืน pointer)
- Linked list, tree operations