zoukankan      html  css  js  c++  java
  • 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
    ",pa);
        printf("int pa+1=%p
    ",(pa+1));
        printf("void pa1->a,%p
    ",pa1);
        printf("void pa1+1=%p
    ",(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 *指针保证了减法运算的结果。
  • 相关阅读:
    layout(布局)组件
    accordion(分类)组件
    progressBar(进度条)组件
    LinkButton(按钮)组件
    tooltip(提示框)组件
    jQuery中animate( )的方法及$("body").animate({'scrollTop':top},500)不被Firefox支持问题的解决
    Echarts 图例交互事件
    JSON 语法
    jQueryMobile (一) :教程
    纯CSS3按钮变换效果
  • 原文地址:https://www.cnblogs.com/litifeng/p/7690624.html
Copyright © 2011-2022 走看看