當char型變數遇上char*型的指標

Archerqvq發表於2024-06-18
#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型別變數的地址)

相關文章