iT邦幫忙

1

C語言 輸出變數x的位址範圍

輸出一個整數變數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的位址範圍呢?

淺水員 iT邦大師 6 級 ‧ 2019-02-06 16:24:00 檢舉
因為 (int*) +1 會直接加 1 個 sizeof(int) 的位址
所以你需要轉成 (char*) 處理
js050233 iT邦新手 5 級 ‧ 2019-02-06 20:42:10 檢舉
感謝,我了解了
那若在不使用指標的情況下請問我該如何轉成char呢?
js050233 iT邦新手 5 級 ‧ 2019-02-06 20:59:00 檢舉
後來試著把&x指派給y(int y=&x)
再修改成y+sizeof(int)-1
雖有warning
但結果似乎是正確的
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
worf_worf
iT邦見習生 ‧ 2019-02-08 01:39:18

有warning 很正常

0
junwu
iT邦見習生 ‧ 2020-10-11 22:33:01

先將&x轉成unsigned long就可以和sizeof(int)進行整數的運算了,所以可以改寫為:
printf("0x%lx", (unsigned long)(&x)+sizeof(int)-1 );

我要發表回答

立即登入回答