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

การดำเนินการคณิตศาสตร์ด้วย Pointers (Pointer Arithmetic) ในภาษา C

Pointer Arithmetic** คือการทำคณิตศาสตร์กับ Pointer Variable ซึ่งแตกต่างจากคณิตศาสตร์ทั่วไป เพราะขึ้นอยู่กับขนาดชนิดข้อมูล (Scale Factor)

พื้นฐาน Pointer

int qty = 179;
int *p = &qty;  // p เก็บที่อยู่ของ qty

การดำเนินการที่ถูกต้อง (Valid Operations)

การดำเนินการตัวอย่างคำอธิบาย
Dereference + คณิตศาสตร์*p1 + *p2บวกค่าที่ Pointer ชี้อยู่
Pointer + Integerp1 + 4เลื่อน Pointer ไป 4 สมาชิกข้างหน้า
Pointer - Integerp2 - 2เลื่อน Pointer ถอยหลัง 2 สมาชิก
Pointer - Pointerp1 - p2จำนวนสมาชิกระหว่าง p1 และ p2 (Same Array)
Increment/Decrementp1++, --p2เลื่อนไป/กลับ 1 สมาชิก
Comparisonp1 > p2, p1 == p2เปรียบเทียบที่อยู่ (Same Array)
Compound Assignmentsum += *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 TypeSize (bytes)Scale Factor
char11
short22
int44
float44
long88
double88
pointer4/84/8

p + 1 หมายถึง Address + (1 × Scale Factor)

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

  • วนลูป Array ด้วย Pointer (เร็วกว่า Indexing เล็กน้อย)
  • String Processing (char * ตัวอักษรติดต่อกัน)
  • Memory Copy (memcpy implementation)
  • Linked List Traversal