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

เข้าใจ Pointer ในภาษา C ด้วยตัวอย่างโปรแกรม


Pointer คืออะไร?

Pointer** คือตัวแปรที่เก็บ **ที่อยู่หน่วยความจำ (Memory Address)** ของตัวแปรอีกตัวหนึ่ง

คุณสมบัติของ Pointer

  • ประหยัดหน่วยความจำ
  • รันเร็วขึ้น เพราะเข้าถึง Memory โดยตรง
  • จัดการ Memory แบบ Dynamic (Allocate/Deallocate)
  • ใช้กับ Data Structures (Linked List, Tree, Graph)

ตัวอย่างที่ 1: เข้าถึงตัวอักษรใน String ด้วย Pointer

#include <stdio.h>

int main() {
    char array[] = "Tutorial"; // 8 chars + \0
    char *ptr, *ptr1;
    int i;
    
    ptr = &array[1];      // ชี้ที่ 'u' (index 1)
    ptr1 = ptr + 3;       // ชี้ที่ 'r' (index 4)
    *ptr1 = 'e';          // เปลี่ยน 'r' → 'e' (ASCII 101)
    
    // พิมพ์ 4 ตัวอักษรตั้งแต่ ptr
    for (i = 0; i < 4; i++)
        printf("%c", *ptr++); // u t o e
    
    return 0;
}

ผลลัพธ์: utoe

ตัวอย่างที่ 2: Pointer Arithmetic

#include <stdio.h>

int main() {
    char string[] = "CprogRamming";
    char *p, *p1;
    int i;
    
    p = &string[5];   // ชี้ที่ 'R' (index 5)
    p1 = p + 3;       // ชี้ที่ 'm' (index 8)
    *p1 = 'e';        // เปลี่ยน 'm' → 'e'
    
    for (i = 0; i < 4; i++)
        printf("%c", *p++); // R a m e
    
    return 0;
}

ผลลัพธ์: Rame

พื้นฐาน Pointer ที่ต้องรู้

Operatorชื่อคำอธิบาย
&Address-ofเอาที่อยู่ของตัวแปร
*Dereferenceเข้าถึงค่าที่ Address ชี้อยู่
ptr + nPointer Arithmeticชี้ไป n ตัวข้างหน้า (ขึ้นกับ sizeof type)
ptr++Post-incrementใช้ค่าก่อน แล้วชี้ถัดไป
++ptrPre-incrementชี้ถัดไปก่อน แล้วใช้ค่า

การประกาศและใช้งานพื้นฐาน


int a = 10;
int *p = &a;     // p เก็บที่อยู่ของ a
printf("%d", *p); // 10 (Dereference)
*p = 20;         // เปลี่ยนค่า a ผ่าน p
printf("%d", a);  // 20

NULL Pointer


int *p = NULL; // หรือ 0, nullptr (C++11)
// ตรวจสอบก่อนใช้เสมอ
if (p != NULL) {
    *p = 10; // Safe
}