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

Pointer to Pointer (Double Pointer) ในภาษา C


Pointer to Pointer (Double Pointer) คืออะไร?

ในภาษา C Pointer to Pointer หรือ Double Pointer คือ ตัวแปรที่เก็บที่อยู่ของ Pointer อีกตัวหนึ่ง (Pointer ชี้ไปที่ Pointer)

การประกาศ (Declaration)

datatype **pointer_name;

ตัวอย่าง: int **p; → p เป็น pointer to pointer

การกำหนดค่าเริ่มต้น (Initialization)

ใช้ตัวดำเนินการ & (Address-of operator)

int a = 10;
int *p;
int **q;
p = &a;   // p ชี้ไปที่ a
q = &p;   // q ชี้ไปที่ p

การเข้าถึงค่า (Accessing)

  • *p → ค่าของ a (10)
  • **q → ค่าของ a ผ่าน q (10)
  • *q → ที่อยู่ของ a (ค่าใน p)
  • q → ที่อยู่ของ p

ตัวอย่างโปรแกรมที่ 1: แสดงความสัมพันธ์พื้นฐาน

#include <stdio.h>
int main() {
    int a = 10;
    int *p;
    int **q;
    p = &a;
    q = &p;
    printf("a = %d\n", a);
    printf("Value via pointer (*p) = %d\n", *p);
    printf("Value via double pointer (**q) = %d\n", **q);
    return 0;
}

ผลลัพธ์:


a = 10
Value via pointer (*p) = 10
Value via double pointer (**q) = 10

ตัวอย่างโปรแกรมที่ 2: แสดงที่อยู่หน่วยความจำแบบละเอียด

#include <stdio.h>
int main() {
    int a = 10;
    int *p = &a;
    int **q = &p;
    
    printf("Value of a: %d\n", a);
    printf("Address of a (p): %p\n", (void*)p);
    printf("Value at p (*p): %d\n", *p);
    printf("Address of p (q): %p\n", (void*)q);
    printf("Value at q (*q = address of a): %p\n", (void*)*q);
    printf("Value at **q: %d\n", **q);
    return 0;
}

ผลลัพธ์ตัวอย่าง (ที่อยู่จะต่างกันทุกครั้งที่รัน):


Value of a: 10
Address of a (p): 0x7ffd1234567c
Value at p (*p): 10
Address of p (q): 0x7ffd12345670
Value at q (*q): 0x7ffd1234567c
Value at **q: 10

สรุปภาพความสัมพันธ์

q (int **) ──→ p (int *) ──→ a (int)
   │             │            │
   │             │            └─ 10
   │             └─ Address of a
   └─ Address of p

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

  • ส่ง pointer ไปฟังก์ชันเพื่อให้ฟังก์ชันเปลี่ยนค่า pointer ต้นทางได้ (เปลี่ยน address ที่ชี้)
  • จัดการ Dynamic 2D Array
  • Linked List, Tree, Graph implementations
  • Command line arguments (char **argv)