輸出一個整數變數x=500的位址範圍,以下為程式碼:
#include<stdio.h>
int main()
{
int x=500;
printf("%x\n", sizeof(int));
printf("An int variable is declared with value equals to %d and \nit is allocated at memory address 0x%p - 0x%p.\n", x, &x, (&x)+sizeof(int)-1);
system("pause");
return 0;
}
輸出結果:
4
An int variable is declared with value equals to 500 and
it is allocated at memory address 0x000000000062FE4C - 0x000000000062FE58.
請按任意鍵繼續 . . .
讓我感到好奇的是,已知sizeof(int)為4bytes,而位址應該也是以byte為單位,為何結果卻不是預期的62FE4C~62FE4F呢?
又或者有其他方法可印出變數x的位址範圍呢?
先將&x轉成unsigned long就可以和sizeof(int)進行整數的運算了,所以可以改寫為:
printf("0x%lx", (unsigned long)(&x)+sizeof(int)-1 );