吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C/C++ 中的void指针

C/C++ 中的void指针

来源:网络 | 更新时间:2022-01-18 07:54:05
void 指针是没有关联数据类型的指针。void 指针可以保存任何类型的地址,并且可以转换为任何类型。
int a = 10;
char b = 'x';

void *p = &a; // void pointer holds address of int 'a'
p = &b; // void pointer holds address of char 'b'
void 指针的优点: 1) malloc() 和 calloc() 返回 void * 类型,这允许这些函数用于分配任何数据类型的内存(仅仅因为 void *)
int main(void)
{
// Note that malloc() returns void * which can be 
// typecasted to any type like int *, char *, ..
int *x = malloc(sizeof(int) * n);
}
请注意,上面的程序用 C 编译,但不能用 C++ 编译。在 C++ 中,我们必须将 malloc 的返回值显式类型转换为 (int *)。 2) C 中的 void 指针用于在 C 中实现泛型函数。例如qsort() 中使用的比较函数 一些有趣的事实: 1) void 指针不能被取消引用。例如以下程序无法编译。
#include<stdio.h>
int main()
{
int a = 10;
void *ptr = &a;
printf("%d", *ptr);
return 0;
}
输出:
Compiler Error: 'void*' is not a pointer-to-object type
以下程序编译并运行良好。
#include<stdio.h>
int main()
{
int a = 10;
void *ptr = &a;
printf("%d", *(int *)ptr);
return 0;
}
输出: 2) C 标准不允许使用 void 指针进行指针运算。但是,在 GNU C 中,考虑到 void 的大小为 1 是允许的。例如,以下程序在 gcc 中编译和运行良好。
#include<stdio.h>
int main()
{
int a[2] = {1, 2};
void *ptr = &a;
ptr = ptr + sizeof(int);
printf("%d", *(int *)ptr);
return 0;
}
输出:
2
 

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com