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

Array of Pointers และ Pointer to Pointer ในภาษา C

Array of Pointers (อาร์เรย์ของพอยน์เตอร์)

อาร์เรย์ที่แต่ละสมาชิกเป็น Pointer ชี้ไปยังตัวแปรชนิดเดียวกัน

การประกาศ

datatype *ptr_name[size];

ตัวอย่าง: int *p[5]; → อาร์เรย์ 5 ตัว ที่แต่ละตัวชี้ไปที่ int

การเริ่มต้นค่า

int a[3] = {10, 20, 30};
int *p[3];

for(int i = 0; i < 3; i++)
    p[i] = &a[i];  // หรือ p[i] = a + i;

การเข้าถึง

for(int i = 0; i < 3; i++)
    printf("%d ", *p[i]);  // Dereference เพื่อได้ค่า

ตัวอย่างโปรแกรม

#include <stdio.h>

int main() {
    int a[3] = {10, 20, 30};
    int *p[3];
    
    for(int i = 0; i < 3; i++)
        p[i] = &a[i];
    
    printf("Array elements via pointers: ");
    for(int i = 0; i < 3; i++)
        printf("%d ", *p[i]);
    
    return 0;
}

ผลลัพธ์

Array elements via pointers: 10 20 30

Pointer to Pointer (พอยน์เตอร์ไปยังพอยน์เตอร์)

ตัวแปรที่เก็บที่อยู่ของ Pointer อีกตัวหนึ่ง เรียกว่า Double Pointer

การประกาศ

datatype **ptr_name;

ตัวอย่าง: int **q;

การเริ่มต้นค่า

int a = 10;
int *p = &a;      // p ชี้ a
int **q = &p;     // q ชี้ p

การเข้าถึง

นิพจน์ค่าคำอธิบาย
a10ค่าเดิม
*p10Dereference ครั้งที่ 1
**q10Dereference ครั้งที่ 2 (q→p→a)
*q&aค่าของ p (Address ของ a)
q&pAddress ของ p

ตัวอย่างโปรแกรม

#include <stdio.h>

int main() {
    int a = 10;
    int *p = &a;
    int **q = &p;
    
    printf("a = %d\n", a);
    printf("*p = %d\n", *p);
    printf("**q = %d\n", **q);
    printf("p = %p\n", (void*)p);
    printf("q = %p\n", (void*)q);
    printf("*q = %p\n", (void*)*q);
    
    return 0;
}

ผลลัพธ์

a = 10
*p = 10
**q = 10
p = 0x7ffc...
q = 0x7ffc...
*q = 0x7ffc... (same as p)

การใช้งานจริงของ Pointer to Pointer

  • เปลี่ยน Pointer ในฟังก์ชัน - ฟังก์ชันต้องการแก้ไข Pointer ตัวแปรของ Caller
  • 2D Array แบบ Dynamic - int **matrix = malloc(rows * sizeof(int*));
  • Linked List Operations - Insert/Delete ที่ Head ต้องเปลี่ยน Head Pointer
  • Command Line Arguments - char **argv ใน main

ตัวอย่าง: แก้ไข Pointer ในฟังก์ชัน

void allocate(int **ptr, int size) {
    *ptr = malloc(size * sizeof(int));  // แก้ไข ptr ของ caller
}

int main() {
    int *arr = NULL;
    allocate(&arr, 10);  // ส่ง address ของ arr
    // arr ตอนนี้ชี้ไปหน่วยความจำที่จองไว้ 10 int
    free(arr);
    return 0;
}