4

Normally, we declare variables like this in C++:

int exampleInteger;

What if I have a pointer to the address of an integer? Can I declare an integer located at a certain memory address?

int* exampleIntegerPtr = (int*) 0x457FB;
int exampleInteger = *exampleIntegerPtr;

Unfortunately, exampleInteger in the second example isn't like exampleInteger in the first example. The second example creates a new variable that has the same value as the integer located at exampleIntegerPtr. Is it possible to somehow grab the actual integer located at exampleIntegerPtr?

2 Answers2

4

Yes, you can do it using references, like this:

int &a(*aPtr);

At this point, any changes done to the int stored at aPtr will be reflected in a:

*aPtr = 123;
cout << a << endl; // 123 is printed
*aPtr = 456;
cout << a << endl; // 456 is printed

Of course in order for this to work you need to ensure that the constant 0x457FB indeed represents a valid address available for reading and writing by your program.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

As dasblinkenlight said you can use references to accomplish what you desire. I would add one things to this, since we are using C++ you should prefer reinterpret_cast over C style casts since you are being explicit about your intention and they are easier to find and stand out more, this previous thread goes into this in more detail. The code would look as follows:

int* exampleIntegerPtr = reinterpret_cast<int*>(0x457FB);
int &exampleInteger = *exampleIntegerPtr;
Community
  • 1
  • 1
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740