Is it possible to convert an integer pointer to an actual integer located in this memory cell?

We usually declare such variables in C ++:

int exampleInteger; 

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

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

Unfortunately, exampleInteger in the second example is not similar to the exampleInteger in the first example. The second example creates a new variable that has the same value as the integer located in exampleIntegerPtr. Is it possible to somehow capture the actual integer located in the IntegerPtr example?

+4
source share
2 answers

Yes, you can do this using links, for example:

 int &a(*aPtr); 

At this point, any changes made to int saved in aPtr will be reflected in a :

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

Of course, for this you need to make sure that the constant 0x457FB really represents a valid address that can be read and written by your program.

+4
source

As dasblinkenlight said, you can use links to achieve what you want. I would add one thing to this, since we use C ++, you should prefer reinterpret_cast over C style , since you clearly indicate your intention and it is easier to find and allocate more, this previous thread goes into this in more detail. The code is as follows:

 int* exampleIntegerPtr = reinterpret_cast<int*>(0x457FB); int &exampleInteger = *exampleIntegerPtr; 
+1
source

Source: https://habr.com/ru/post/1485134/


All Articles