C语言--void指针参数

C语言–函数的传参(pointer)

c语言中有一种通用指针,void * 类型指针,该指针在C中很常见,通常用于针对不同类型参数的函数。
例如,以下函数将对任何类型的数据清零。

void test(void *data, size_t n)
{
    memset(data, 0x00, n);
}

可以将任何类型的指针传递给test函数而不需要cast。

    int ax = 10;
    test(&ax, sizeof(ax));
    printf("ax = %d\n", ax);
    void *ptr = &ax;
    return 0;

但是, void** 是另一种情况。

void changeptr(void **ptr)
{
    *ptr = NULL;
}
    int ax = 10;
    void *ptr = &ax;
    int *iptr = ptr;
    printf("%d\n", *iptr);
    test(&ax, sizeof(ax)); 
    changeptr(&iptr);
    printf("ax = %d\n", ax);
    return 0;
warning: incompatible pointer types pass 'int **' to parameter of type 'void **'
gcc testvoid.c -o testvoid
testvoid.c: In function ‘main’:
testvoid.c:19:15: warning: passing argument 1 of ‘changeptr’ from incompatible pointer type [-Wincompatible-pointer-types]
     changeptr(&iptr);
                    ^
testvoid.c:10:6: note: expected ‘void **’ but argument is of typeint **’
void changeptr(void **ptr)

因此,对于void ** 参数必须进行强制类型转换

changeptr((void **)&iptr);

A cast is necessary here because, although a void pointer is compatible with any other type of pointer in C, a pointer to a void pointer is not.

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值