void *指針的加減運算
阿新 • • 發佈:2017-10-19
clu inter fine match build 函數 this noi return
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 *指針的加減運算