Topic : How Pointers Work
Author : John Coltharp
Page : 1

How Pointers Really Work
by OutAxDx

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:

void *Pointer;

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:

void _far *MakeFarPointer(unsigned short OFFSET, unsigned short SEGMENT)
   union tagUNION
      struct tagADDRESS
         unsigned short OFFSET, SEGMENT;
      } ADDRESS;
      void _far *POINTER;
   } UNION;
   return UNION.POINTER;

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:

unsigned long _far *somepointer = (unsigned long _far *)MakeFarPointer(0xA000, 0x0000);

In Win32, with the 32bit memory, it is very simple to point to a location:

unsigned long *somepointer = (unsigned long *)0xA389B036;

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:

int variable = 10;
int *somepointer = &variable;

This makes somepointer point to the address of variable. The & symbol means "address of". Now look at the following:

somepointer[0] = 25;

This means variable will no longer be 10, but is now 25. Get it? If not, then I guess I suck at writing articles.

Page : 1