#include <stdio.h>
int main(void)
{
char* i = (char*)0x1111;
printf("size = %d %d\n", sizeof(i), sizeof((char*)0x11));
// size i = 8 bytes, size(char*)0x11 = 8bytes, cause 0x11 is convered to char*, char* is a poninter and has 64 bits in x64 system
printf("value = %p %p\n\n", i, (char*)0x1111); // pointer i = 0000000000001111, pointer(char*)0x11 = 0000000000001111
printf("---------------------------------------------------------------\n");
char* j = (char)0x1111;
printf("size = %d %d \n", sizeof(j), sizeof((char)0x11)); // size j = 8bytes, size(char)0x11) = 1 bytes
// char is 8 bits
printf("value = %p %p \n", j, (char)0x1111); // value = 0000000000000011 0000000000000011
// (char)0x1111 is cut off when it is over 8 bits, so when char* j = (char)0x1111, the pointer of j is 0000000000000011
return 0;
}
结论:
-
char型变量有8bits,char*型指针变量有64bits(在x64系统下),将一个char类型的变量赋值给指针,那么该指针指向的地址只有0~255种可能,这是不应该的
-
正确写法应该是char类型指针对应char类型指针,即: char i = (char)0x0000000000001111; 这样64位对应64位,指针i就能正常寻址,而不是只能访问部分地址
注:char i表示 -> 指针i的类型是char,其指向数据类型为char的变量(存放char类型变量的地址)