I have just started learning C++ so I may be way off the mark with this one but go easy on me.
What I want to do is to write to a memory address that I specify – if that’s possible?
The code I am using is:
#include <iostream>
int main()
{
using namespace std;
int i = 100;
int* p = &i;
cout << p << "\n";
cout << "Writing" << "\n";
int* w = (int*)0x28ff18;
*w = 101;
cout << *p << "\n" << "Done";
return 0;
}
The address I get for i is 0x28ff18, so is it possible to write to that location by specifying this address? Rather than use *p = 101. Obviously what I am using doesn’t change it, I don’t know where or if it’s writing 101.
Any simple explanation or help is much appreciated.
On most computers and with most compilers, something like this will probably work. But the C++ standard does not guarantee anything about this.
For example, when I compiled and ran your code using MSVC++ on a Windows machine, every time the address was different. You cannot expect it to be the same between different runs of the same program.
Also note that the integer you are storing the pointer value in should be large enough (e.g., a 64-bit integer when you have 64-bit pointers). Use uintptr_t if you want to do this (thanks larsmans for pointing this out).