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 *指针保证了减法运算的结果。

 

posted @ 2017-10-19 08:53  立体风  阅读(9184)  评论(0编辑  收藏  举报