How Pointers Really Work
The purpose of this article is to explain pointers of course. There isn't much good information out there, and tons of confused people ask me about them, so I thought I'd write this up. A pointer is simply a variable in C or C++ which has an asterisk before it. An example would be something like this:
What a pointer does, simply put, is point to a memory location. All pointers, no matter what data type you use for them, whether it be void, int, long, char, or whatever, are 4 bytes in size. These 4 bytes contain the memory location pointed to. In DOS, with _far pointers, the first 2 bytes are the offset address. The last 2 bytes contain the segment address. In 32bit operating systems, such as Windows 95/95/NT/2000, also known in programming as Win32, all 4 bytes together contain the address, since 32bit memory is linear. There are no offsets or segments in 32bit memory. Here is an example of a DOS function to return a pointer to the specified memory address:
Now in a lot and most DOS compilers, you can simply have a pointer equal the numeric value of the address, like you can in Win32. The early Microsoft Visual C++ compilers that supported DOS didn't do well with doing that though. It pointed at the number, instead of pointing to where the number says to go. I play it safe using the above function. To point a pointer at a location using this function, you would do the following:
In Win32, with the 32bit memory, it is very simple to point to a location:
Now, you've got a pointer of type unsigned long. The best way to now treat this as a non-pointer, and place data in it, is to use the array brackets. Just do "somepointer[0] = number;", or otherwise anything you have it equal becomes its new address it points to. Using array brackets is the easiest way to avoid doing that. So really, a pointer is just a way to choose where a variable is stored. Here is some code to look at:
This makes somepointer point to the address of variable. The & symbol means "address of". Now look at the following:
This means variable will no longer be 10, but is now 25. Get it? If not, then I guess I suck at writing articles. Discuss this article in the forums
See Also: © 1999-2011 Gamedev.net. All rights reserved. Terms of Use Privacy Policy
|