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

Void Pointer ในภาษา C

ความหมาย

Void pointer (void *) คือ pointer แบบ generic ที่สามารถชี้ไปยังตัวแปรชนิดข้อมูลใดๆ ได้ ไม่มีชนิดข้อมูลเฉพาะ

การประกาศ

void *ptr_name;

ตัวอย่าง: void *vp;

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

ต้องใช้ Type Casting ก่อน dereference เพราะคอมไพเลอร์ไม่รู้ขนาดข้อมูล

*((type_cast) void_pointer)

ตัวอย่างที่ 1: 基本用法

int i = 10;
void *vp;
vp = &i;
printf("%d", *((int*)vp)); // cast เป็น int* แล้ว dereference

ตัวอย่างโปรแกรมที่ 1: Void Pointer ชี้ไปยังชนิดต่างๆ

#include <stdio.h>
int main() {
    int i = 10;
    float f = 5.34;
    void *vp;
    vp = &i;
    printf("i = %d\\n", *((int*)vp));
    vp = &f;
    printf("f = %f\\n", *((float*)vp));
    return 0;
}

ผลลัพธ์

i = 10
f = 5.340000

ตัวอย่างโปรแกรมที่ 2: Pointer Arithmetic กับ Void Pointer

#include <stdio.h>
#define MAX 20
int main() {
    int array[5] = {12, 19, 25, 34, 46};
    void *vp = array; // array decay to pointer to first element
    for (int i = 0; i < 5; i++) {
        // ต้อง cast เป็น int* ก่อนทำ pointer arithmetic
        printf("array[%d] = %d\\n", i, *((int*)vp + i));
    }
    return 0;
}

ผลลัพธ์

array[0] = 12
array[1] = 19
array[2] = 25
array[3] = 34
array[4] = 46

ข้อจำกัดของ Void Pointer

  • ไม่สามารถ dereference ได้โดยตรง ต้อง cast ก่อน
  • ไม่สามารถทำ pointer arithmetic ได้โดยตรง (ไม่รู้ขนาด type) ต้อง cast ก่อน
  • ไม่สามารถใช้ -> หรือ [] ได้โดยตรง

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

  • Generic functions: qsort, bsearch ใช้ void* เพื่อรองรับทุก type
  • Memory allocators: malloc, calloc, realloc คืน void*
  • Callback functions: ส่ง context เป็น void*
  • Polymorphism ใน C: โครงสร้างที่มี void* data

ตัวอย่าง Generic Swap

void swap(void *a, void *b, size_t size) {
    char temp[size];
    memcpy(temp, a, size);
    memcpy(a, b, size);
    memcpy(b, temp, size);
}
// ใช้ได้กับทุก type
int x=1, y=2; swap(&x, &y, sizeof(int));
float f1=1.0, f2=2.0; swap(&f1, &f2, sizeof(float));