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

“void *” แตกต่างกันอย่างไรใน C และ C++


ในส่วนนี้เราจะดูความแตกต่างระหว่าง void pointer ใน C และ C++ ทั้งคู่เป็น void pointers แตใน C void pointer สามารถ assign ให้ pointer type ใดๆ ได้ แต่ใน C++ ไม่สามารถทำได้ ต้อง explicitly typecast

ตัวอย่างบรรทัดต่อไปนี้ทำงานใน C:

void *p; int *int_ptr = p;

ถ้าใช้ malloc() จัดสรรหน่วยความจำ สามารถ explicit typecast ได้ แต่ไม่ทำก็ได้ malloc() คืน void pointer

int *int_ptr = malloc(sizeof(int) * 10);

void pointer ที่คืนมา implicit convert เป็น integer type pointer

ถ้าต้องการรันโปรแกรมเดียวกันใน C และ C++ ควร explicit typecast pointers:

void *p; int *int_ptr = (int *) p; int *arr_ptr = (int *) malloc(sizeof(int) * 10);