【问题标题】:Pointer to a given memory address -C++指向给定内存地址的指针-C++
【发布时间】:2014-03-16 15:59:56
【问题描述】:

指针的基本语法:*ptr= &a

这里&a将返回变量a的内存地址,*ptr将存储变量a的值

我想问,是否可以让指针从给定的内存地址返回值?如果是,语法是什么

【问题讨论】:

标签: c++ c pointers


【解决方案1】:

是的,你可以构造一个指向内存中任意地址的指针,方法是直接用地址初始化指针,而不是用像&a这样的表达式:

int* ptr = (int*)0x1234ABCD;  // hex for convenience
std::cout << *ptr;

不过要小心,因为您很少能准确地知道这样的内存地址。

(int*) 是必需的,因为 intint* 之间不存在隐式转换。

【讨论】:

  • 嵌入式系统很少见吗?因为这经常用于访问硬件寄存器。 :-)
  • @ThomasMatthews:是的,我知道这一点。我每天都使用它们。这就是为什么我说“罕见”而不是“从不”。那是 one 用例,坦率地说,我不知道其他任何用例。这就是为什么我说它很少见。
  • 感谢您的回答,这就是我要找的。​​span>
【解决方案2】:

是的。使用取消引用运算符*。 例如;

int * a = new int;
int * b = new int;
*a = 5;
// Now a points to a memory location where the number 5 is stored.
b = a; //b now points to the same memory location.
cout << *b << endl; ///prints 5.
cout << a << " " << b << endl; //prints the same address.

int * c = new int;
c = *a;
// Now c points to another memory location than a, but the value is the same.
cout << *c << endl; ///prints 5.
cout << a << " " << c << endl; //prints different addresses.

【讨论】:

  • 但是在这里我们直接为 *a 提供值,而不是我想为 *a 提供一些内存地址,并使其存储该值
  • 哦,我明白了。我会添加这个。
猜你喜欢
  • 1970-01-01
  • 2020-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
相关资源
最近更新 更多