2013-04-09 167 views
0

如何打印用戶輸入的地址?這種方式不起作用。打印用戶在C++中鍵入的內存地址的內容

這是代碼。謝謝。

#include <iostream> 

using namespace std; 

int main() 
{ 
    int num = 123456; 
    int *addr = &num; 

    cout << "Var: num, address: " << &num << ", has: " << num << endl 
     << "Var: *addr, address: " << &addr << ", has: " << addr << endl 
     << "Printing value of num using the pointer *addr: " << *addr << endl; 

    int addr_user; 
    cout << "Type the memory address: "; cin >> addr_user; 

    int *p_addr_user = (int *)addr_user; 

    cout << "The address given (" << addr_user << ") has: " << *p_addr_user << endl; 
    return(0); 
} 

對不起,我不是很清楚:

什麼程序必須做到: 要求輸入一個整數,從這些整數打印內存地址,請鍵入上面印着的內存地址,打印該內存地址的內容,並確認該地址是否有第一步輸入的號碼。

所有在一個運行時。先謝謝你。

+0

啊,我很抱歉,我不明白你的要求第一時間,所以我的回答根本不是你在找什麼:) – AkiRoss 2013-04-25 23:48:53

回答

1

我在Linux的嘗試了這一點:

g++ q.cpp 
q.cpp: In function ‘int main()’: 
q.cpp:17:31: warning: cast to pointer from integer of different size [-Wint-to-pointer- cast] 
./a.out 
Var: num, address: 0x7fff562d2828, has: 123456 
Var: *addr, address: 0x7fff562d2818, has: 0x7fff562d2828 
Printing value of num using the pointer *addr: 123456 
Type the memory address: 0x7fff562d2828 
Segmentation fault (core dumped) 

所以我注意到幾個問題:

  1. 我當然想嘗試把在NUM的地址,但它會顯示在六角
  2. 賽格故障

要以十六進制輸入我的輸入線更改爲:

cout << "Type the memory address: "; cin >> hex >> addr_user; 

(否則被解釋爲0)

但它仍然段錯誤。

這裏的問題:

int *p_addr_user = (int*)addr_user; 

哦,有一個關於它上面的警告。某些時候大約有不同的尺寸(注意指針是無符號的)。

整型和指針可以是不同的大小(它取決於你的平臺)對於我來說int是32位,指針是64位。

這裏就是我得到了它的工作:

#include <stdint.h> 
#... 
uintptr_t addr_user; 
cout << "Type the memory address: "; cin >> hex >> addr_user; 
uintptr_t *p_addr_user =(uintptr_t*) addr_user; 
+0

感謝。 :)這幫了很多。 – RMCampos 2013-04-15 17:04:12