C语言函数调用中的指针转换
示例
到的指针转换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;
}
热门推荐
10 五一公司放假祝福语简短
11 追星女孩的祝福语简短
12 给长辈端午祝福语 简短
13 生日祝福语有诗意简短
14 团圆日祝福语简短
15 中秋商务祝福语简短最新
16 温暖文艺简短祝福语短句
17 男孩上学祝福语简短的
18 入住酒店文案祝福语简短