Pointer Arithmetic** คือการทำคณิตศาสตร์กับ Pointer Variable ซึ่งแตกต่างจากคณิตศาสตร์ทั่วไป เพราะขึ้นอยู่กับขนาดชนิดข้อมูล (Scale Factor)
พื้นฐาน Pointer
int qty = 179;
int *p = &qty; // p เก็บที่อยู่ของ qty
การดำเนินการที่ถูกต้อง (Valid Operations)
| การดำเนินการ | ตัวอย่าง | คำอธิบาย |
| Dereference + คณิตศาสตร์ | *p1 + *p2 | บวกค่าที่ Pointer ชี้อยู่ |
| Pointer + Integer | p1 + 4 | เลื่อน Pointer ไป 4 สมาชิกข้างหน้า |
| Pointer - Integer | p2 - 2 | เลื่อน Pointer ถอยหลัง 2 สมาชิก |
| Pointer - Pointer | p1 - p2 | จำนวนสมาชิกระหว่าง p1 และ p2 (Same Array) |
| Increment/Decrement | p1++, --p2 | เลื่อนไป/กลับ 1 สมาชิก |
| Comparison | p1 > p2, p1 == p2 | เปรียบเทียบที่อยู่ (Same Array) |
| Compound Assignment | sum += *p2 | บวกค่าที่ชี้อยู่เข้า sum |
การดำเนินการที่ผิด (Invalid Operations)
| การดำเนินการ | เหตุผล |
| p1 + p2 | ไม่มีความหมายที่จะบวกที่อยู่ 2 ตัว |
| p1 * p2 | คูณที่อยู่ไม่ได้ |
| p1 / p2 | หารที่อยู่ไม่ได้ |
| p1 / 3 | หาร Pointer ด้วยตัวเลขไม่ได้ |
ตัวอย่างโปรแกรม
#include <stdio.h>
int main() {
int a = 12, b = 4;
int *p1 = &a, *p2 = &b;
int x, y;
// คณิตศาสตร์กับค่าที่ Pointer ชี้
x = *p1 * *p2 - 6; // 12 * 4 - 6 = 42
y = 4 - *p2 / *p1 + 10; // 4 - 4/12 + 10 = 14 (integer division)
printf("Address of a = %p\n", (void*)p1);
printf("Address of b = %p\n", (void*)p2);
printf("a = %d, b = %d\n", a, b);
printf("x = %d, y = %d\n", x, y);
// Pointer Arithmetic
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr;
printf("\nPointer Arithmetic Demo:\n");
printf("ptr = %p, *ptr = %d\n", (void*)ptr, *ptr);
printf("ptr+1 = %p, *(ptr+1) = %d\n", (void*)(ptr+1), *(ptr+1));
printf("ptr+2 = %p, *(ptr+2) = %d\n", (void*)(ptr+2), *(ptr+2));
printf("ptr+3 - ptr = %ld elements\n", (ptr+3) - ptr); // 3
return 0;
}
ผลลัพธ์
Address of a = 0x7ffc...
Address of b = 0x7ffc...
a = 12, b = 4
x = 42, y = 14
Pointer Arithmetic Demo:
ptr = 0x7ffc..., *ptr = 10
ptr+1 = 0x7ffc..., *(ptr+1) = 20
ptr+2 = 0x7ffc..., *(ptr+2) = 30
ptr+3 - ptr = 3 elements
Scale Factor (ตัวคูณขนาดชนิดข้อมูล)
| Data Type | Size (bytes) | Scale Factor |
| char | 1 | 1 |
| short | 2 | 2 |
| int | 4 | 4 |
| float | 4 | 4 |
| long | 8 | 8 |
| double | 8 | 8 |
| pointer | 4/8 | 4/8 |
p + 1 หมายถึง Address + (1 × Scale Factor)
การประยุกต์ใช้จริง
- วนลูป Array ด้วย Pointer (เร็วกว่า Indexing เล็กน้อย)
- String Processing (char * ตัวอักษรติดต่อกัน)
- Memory Copy (memcpy implementation)
- Linked List Traversal