到的指针转换void*是隐式的,但任何其他指针转换都必须是显式的。尽管编译器允许从任何指针到数据类型到任何其他指针到数据类型的显式转换,但通过错误键入的指针访问对象是错误的,并导致未定义的行为。唯一允许的情况是类型兼容,或者查看对象所使用的指针是字符类型。
#include <stdio.h> void func_voidp(void* voidp) { printf("%s Address of ptr is %p\n", __func__, voidp); } /* Structures have same shape, but not same type */ struct struct_a { int a; int b; } data_a; struct struct_b { int a; int b; } data_b; void func_struct_b(struct struct_b* bp) { printf("%s Address of ptr is %p\n", __func__, (void*) bp); } int main(void) { /* Implicit ptr conversion allowed for void* */ func_voidp(&data_a); /* * Explicit ptr conversion for other types * * Note that here although the have identical definitions, * the types are not compatible, and that the this call is * erroneous and leads to undefined behavior on execution. */ func_struct_b((struct struct_b*)&data_a); /* My output shows: */ /* func_charp Address of ptr is 0x601030 */ /* func_voidp Address of ptr is 0x601030 */ /* func_struct_b Address of ptr is 0x601030 */ return 0; }