问题
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