I’m very new to C++ so I do apologize if I’m missing something very obvious.
I was reading a tutorial on C++ which talks about pointers and such.
In the tutorial the following example is given:
andy = 25;
ted = &andy;
beth = *ted;
I noticed that beth is really the same as &andy. So I modified the code to read:
andy = 25;
beth = *(&andy);
When I print out &andy it gives me the memory location that andy refers to.
Each time I executed the code I got a specific memory location: 0x28ff18
Even when I change the name of the variable the memory location (which is what I assume this is) doesn’t change. According to the tutorial, the memory location is automatically assigned by the operating system. What can I change in the code I have to change the memory location that andy is at?
However, my main question is as follows: I tried to substitute &andy for the memory location in the code by changing it to.
andy = 25;
beth = *(0x28ff18);
I did this assuming that beth would hold the value of 25, which is the last value lingering in the memory location 0x28ff18.
However, I got an error when I tried to run this code.
I also tried setting 0x28ff18 as a string, a character, and an integer, and in no instance did beth = *(thatVariable); work.
I apologize if I’m not explaining things clearly enough, but I’m wondering if there’s a way I can accomplish what I’m trying to do.
Names of things are compile-time artifacts. Once the compiler is done, it does not matter whether the variable has been called
andy,dummy, orx100019092304928304928341.Add more variables in front of it. This is not guaranteed to work, because the system can place your variable at any logical address, but it has a decent chance of making your variable move.
You need to cast
0x28ff18to a pointer, like this: ((int*)0x28ff18). This will compile, but it may not work. In general, hard-coding fixed addresses is dangerous except when you are accessing memory-mapped hardware through registers placed at fixed addresses.1 Except for debugging. Even then it’s you who cares most about the name of that variable.