Can I directly assign an address to a pointer? If so, how to do that?

微笑、不失礼 提交于 2021-02-05 08:17:27

问题


int main()
{
  int a = 2; // address is 0x7ffeefbff58c
  int *b = &a;
  std::cout << "address of a: " << b << std::endl;
  return 0;
}

I have my int variable a at address 0x7ffeefbff58c, but can I directly assign int* b with 0x7ffeefbff58c?

I tried int * b = 0x7ffeefbff58c; But there is an error says "cannot initialize a variable of type 'int *' with an rvalue of type 'long'", so do I have to use the address of a (&a) to initialize the pointer? or there is other way to do it?


回答1:


can I directly assign int* b with 0x7ffeefbff58c?

Technically, yes.

If so, how to do that?

With reinterpret cast.

But do realise that there is absolutely no guarantee in general that a would be in the address 0x7ffeefbff58c. As such, there isn't much that you can do with such integer reinterpreted as a pointer. Doing this with a local variable would be pointless.

A case where interpreting integer as a pointer is useful is some embedded systems that reserve some constant memory addresses for special purposes.




回答2:


Heere is an example:

#include <iostream>
int main()
{

  int *b = (int*) 0x7ffeefbff58c;
  std::cout << "b: " << b << std::endl;
  return 0;
}

after compilation and execution you will see output:

b: 0x7ffeefbff58c



来源:https://stackoverflow.com/questions/58958980/can-i-directly-assign-an-address-to-a-pointer-if-so-how-to-do-that

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!