【问题标题】:Print the content of a memory address typed by user in C++打印用户在 C++ 中键入的内存地址的内容
【发布时间】:2013-04-09 12:46:05
【问题描述】:

如何打印用户输入的地址?这种方式行不通。

这是代码。谢谢。

#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 );
}

对不起,我不是很清楚:

程序必须做什么: 要求输入一个整数,从这些整数中打印内存地址,要求输入上面打印的内存地址,打印该内存地址的内容并确认该地址是否具有在第一步中输入的数字。

一站式运行。提前谢谢你。

【问题讨论】:

  • 啊,对不起,我第一次没有理解你的要求,所以我的回答根本不是你要找的:)

标签: pointers memory hex


【解决方案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的地址,但是显示的是16进制
  2. 段错误

要以十六进制输入,我将输入行更改为:

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

(否则解释为0)

但它仍然是段错误。

问题来了:

int *p_addr_user = (int*)addr_user;

哦,上面有一个警告。有时关于不同的大小(还要注意指针是无符号的。)

int 和指针可以有不同的大小(取决于你的平台)对我来说 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;   

【讨论】:

  • 谢谢。 :) 这很有帮助。
猜你喜欢
  • 1970-01-01
  • 2013-11-13
  • 2015-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-21
  • 1970-01-01
相关资源
最近更新 更多