void *指針的加減運算

一、手工寫了一個程序驗證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;
}

輸出:this

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

由上可知,當一個int指針被強轉爲void型指針後,加1,由之前移動4個字節變爲了移動1個字節。spa

結論:void *指針加減1,移動1個字節,這個在一些計算地址的宏和函數裏會用到。指針

例如:container_of宏:code

/**
 * 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 *指針保證了減法運算的結果。
相關文章
相關標籤/搜索