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

การเข้าถึงหน่วยความจำด้วย Pointer ในภาษา C


Pointer Declaration, Initialization, Accessing

1. Declaration

int *p; // p เป็น Pointer ชี้ไปที่ int

2. Initialization


int qty = 175;
int *p = &qty; // p เก็บ Address ของ qty

3. Accessing (Dereference)


printf("Value: %d\n", *p); // 175
*p = 200;                  // เปลี่ยนค่า qty ผ่าน p
printf("New qty: %d\n", qty); // 200

ภาพจำลองหน่วยความจำ

Variable: qty (int)
Address:  0x7ffd1234
Value:    175

Pointer:  p (int *)
Address:  0x7ffd5678
Value:    0x7ffd1234 (Address of qty)

*p → ไปที่ 0x7ffd1234 → อ่านค่า 175

ตัวอย่าง: Pointer Arithmetic กับ String

#include <stdio.h>

int main() {
    char s[] = {'a', 'b', 'c', '\n', 'c', '\0'};
    char *p, *str, *str1;
    
    p = &s[3];      // p ชี้ที่ '\n' (index 3, ASCII 10)
    str = p;        // str ชี้ที่เดียวกับ p
    str1 = s;       // str1 ชี้ที่ 'a' (index 0, ASCII 97)
    
    // ++*p: เพิ่มค่าที่ p ชี้ (\n=10 → 11)
    // ++*str1: เพิ่มค่าที่ str1 ชี้ (a=97 → 98)
    // ผลรวม - 32 = 11 + 98 - 32 = 77
    printf("%d\n", ++*p + ++*str1 - 32);
    
    return 0;
}

ผลลัพธ์: 77

อธิบายการคำนวณ

s[3] = '\n' (ASCII 10)
s[0] = 'a'  (ASCII 97)

++*p      → ++('\n') → 10+1 = 11
++*str1   → ++('a')  → 97+1 = 98
11 + 98 - 32 = 77

Pointer Arithmetic พื้นฐาน

ExpressionResultหมายเหตุ
ptr + 1Address ถัดไป+ sizeof(type) ไบต์
ptr - 1Address ก่อนหน้า- sizeof(type) ไบต์
ptr2 - ptr1จำนวน Elements ระหว่างกันType ต้องเหมือนกัน
ptr++Post-incrementใช้ค่าก่อน เลื่อนทีหลัง
++ptrPre-incrementเลื่อนก่อน ใช้ค่าทีหลัง

Best Practices

  • Initialize Pointer เสมอ (NULL หรือ Address ที่ถูกต้อง)
  • Check NULL ก่อน Dereference
  • ใช้ const ถ้าไม่ต้องการแก้ค่า: const int *p
  • หลีกเลี่ยง Pointer Arithmetic ที่ซับซ้อนเกินไป