之前看到《系統(tǒng)程序員成長計劃這本書》,里面常用void *指針,然后再轉(zhuǎn)為int時直接使用強轉(zhuǎn)使用,比如void *int_pt;,使用時直接強轉(zhuǎn)(int)int_pt。我對此有點懷疑,所以自己寫了個小程序驗證了一下。證明這種用法是錯誤的。
-
void *int_pt;,使用時直接強轉(zhuǎn)(int)int_pt,(int)int_pt值是地址值,就是int_pt指向的地址的數(shù)值。 - 正確使用該地址所在的int數(shù)應(yīng)該是
*(int *)int_pt,包括賦值和讀取值都應(yīng)該用這種方式。
附上測試源碼:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
void *testvalue;
testvalue = malloc(sizeof(int));
*(int *)testvalue = 134;
printf("%d\n", (int)testvalue);
printf("%d\n", *(int *)testvalue);
free(testvalue);
return 0;
}
運行結(jié)果:
$ ./test
12738576
134