Tuesday, July 14, 2009

Is this what a C++ pointer is in a nutshell?

I ran this test on my compiler





#include %26lt;iostream%26gt;





using namespace std;








int main()


{


int x, y, *z;


y=8;


z=%26amp;y;


x=y;








cout%26lt;%26lt; "x= "%26lt;%26lt; x %26lt;%26lt; " " %26lt;%26lt; "y= " %26lt;%26lt; y %26lt;%26lt; " " %26lt;%26lt; "pointer z= " %26lt;%26lt; *z %26lt;%26lt;"\n"%26lt;%26lt;endl;


system ("PAUSE");


return 0;


}


And all of them returned 8. I then tried to see what would happen if I did





int main()


{


int x, y, *z, *q;


y=8;


z=%26amp;y;


x=y;


*q=z








cout%26lt;%26lt; "x= "%26lt;%26lt; x %26lt;%26lt; " " %26lt;%26lt; "y= " %26lt;%26lt; y %26lt;%26lt; " " %26lt;%26lt; "pointer z= " %26lt;%26lt; *z %26lt;%26lt;" " %26lt;%26lt; "pointer q= "%26lt;%26lt;*q%26lt;%26lt;"\n"%26lt;%26lt;endl;


system ("PAUSE");


return 0;


}


But the DOS window stopped and became unresponsive.


Taking what I got from the first test, I made this analogy, and I assumed


z:%26amp;y::*z:y


Basically, I deduced that z stores the address of y, and *z points to the data stored in the address of the variable y(0x22ff50).


So basically, is a pointer just something that points to the data stored in a memory address?

Is this what a C++ pointer is in a nutshell?
A pointer is just something that stores the address at which another variable's value can be accessed. It points to the actual data stored at that address when you use the dereference operator (*). They are often useful when changing individual memory address, like when making cheats through code injection. For example, the money value in GTA:San Andreas might be something like 0x006FFF. They I could change the money using:


*(int*)0x006FFF = 1337;


This means that it wants to change the value at the address held by 0x006FFF.


No comments:

Post a Comment