void *指针的加减运算

1、手工写了一个程序验证void *指针加减运算移动几个字节:

//本程序验证空类型指针减1移动几个字节                                                              
#include <stdio.h>
int main(int argc, char *argv[])
{
    int a=10,b=20;
    int *pa=&a;
    void * pa1=(void *)pa;
    printf("int pa->a,%p\n",pa);
    printf("int pa+1=%p\n",(pa+1));
    printf("void pa1->a,%p\n",pa1);
    printf("void pa1+1=%p\n",(pa1+1));

    return 0;
}

输出:

fly@noi:~$ ./p1
int pa->a,0x7ffde5e8db10
int pa+1=0x7ffde5e8db14
void pa1->a,0x7ffde5e8db10
void pa1+1=0x7ffde5e8db11

由上可知,当一个int指针被强转为void型指针后,加1,由以前移动4个字节变为了移动1个字节。

结论:void *指针加减1,移动1个字节,这个在一些计算地址的宏和函数里会用到。

例如:container_of宏:

/**
 * container_of - cast a member of a structure out to the containing structure
 * @ptr:    the pointer to the member.
 * @type:    the type of the container struct this is embedded in.
 * @member:    the name of the member within the struct.
 *
 */
#define container_of(ptr, type, member) ({                \
    void *__mptr = (void *)(ptr);                    \
    BUILD_BUG_ON_MSG(!__same_type(*(ptr), ((type *)0)->member) &&    \
             !__same_type(*(ptr), void),            \
             "pointer type mismatch in container_of()");    \
    ((type *)(__mptr - offsetof(type, member)));   //__mptr指针为void *指针保证了减法运算的结果。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值