首页 > 其他 > 详细

void *指针的加减运算

时间:2017-10-19 09:14:38      阅读:307      评论:0      收藏:0      [点我收藏+]

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

 

void *指针的加减运算

原文:http://www.cnblogs.com/litifeng/p/7690624.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!