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

Void pointer ใน C


Void pointer ใน C คือ pointer ที่ไม่เกี่ยวข้องกับ data types ใดๆ ชี้ไปที่ data location ใน storage หมายถึง address ของ variables เรียกว่า general purpose pointer ใน C malloc() และ calloc() คืน void * หรือ generic pointers

มีข้อจำกัด:

1) Pointer arithmetic ไม่ได้กับ void pointer เนื่องจาก concrete size

2) ไม่สามารถ dereference ได้โดยตรง

Algorithm

Begin    Declare a of the integer datatype.       Initialize a = 7.    Declare b of the float datatype.       Initialize b = 7.6.    Declare a pointer p as void.    Initialize p pointer to a.    Print “Integer variable is”.       Print the value of a using pointer p.    Initialize p pointer to b.    Print “Float variable is”.       Print the value of b using pointer p End.

ตัวอย่างง่าย:

ตัวอย่างโค้ด

#include<stdlib.h> int main() {    int a = 7;    float b = 7.6;    void *p;    p = &a;    printf("Integer variable is = %d", *( (int*) p) );    p = &b;    printf("\nFloat variable is = %f", *( (float*) p) );    return 0; }

ผลลัพธ์

Integer variable is = 7 Float variable is = 7.600000