2013-04-09 48 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