SatView: Pointer Perfect, Part 1 - Operations on pointers
(Page 2 of 5 )
Lets start with a code example...I like code examples.
int main(int argc, char *argv[]) {
int myVar = 10;
I nt *pPtr = &myVar;
return 0;
}
When you compile this and look at the memory address pPtr contains in the debugger (or should I say points at), you will find something that resembles:
0x0012FEC4 cccccccc ÌÌÌÌ
0x0012FEC8 0012fed4 Ôþ.. pPtr addr:0x0012FEC8 value:0x0012FED4
0x0012FECC cccccccc ÌÌÌÌ
0x0012FED0 cccccccc ÌÌÌÌ
0x0012FED4 0000000a .... myVar addr:0x0012FED4 value:10
0x0012FED8 cccccccc ÌÌÌÌ
The hexadecimal numbers on the left represent the addresses of sequential memory (note how I have chosen to display 4 bytes – 1 integer per line here). In the middle you find the values stored at that location, and next to that, its ASCII representation.
So a pointer is a variable that stores an address and can be null. In this case you see that pPtr (at 0x0012FEC8) contains the address of myVar (at 0x0012FED4). Note that although the address pointed at looks like an integer (i.e. 4 bytes long) you may not presume this is always the case (e.g. on an IBM AS/400 a pointer is 16 bytes long).
The address dereference operator
How do we play with pointers? One way is to retrieve the address of a variable and store that in a pointer. That is what you use the address dereference operator (&) for.
In the example ‘&myVar’ returns the address of ‘myVar’ (0x0012FED4) which is then stored in ‘pPtr’; this is a pointer that can hold the address to an int. From now on we can access the contents of myVar through pPtr by using the reference operator (see below). It might seem confusing that you would want to have access to a value in two different ways, but it will prove to be very useful.
The reference operator: *
The reference operator is also known as the indirection operator. You use this operator to retrieve the value stored at the address contained in the pointer. Thus ‘*pPtr’ will yield the value 10, which is the value stored in variable myVar at address 0x0012FED4. (Notice that this operator was also used for declaring the pointer.)
It is a good habit to set any uninitialized pointer to 0 (NULL), because otherwise you might be poking around in a random piece of memory when accessing it through the pointer. This would be a good moment to use an assert to make sure the pointer is not 0 (using #include <assert.h>):
int *pPtr = 0;
/* some code here */
assert(pPtr != 0);
*pPtr = 10;
Next: The pointer-to-member operator >>
More Code Examples Articles
More By J. Nakamura