Skip to content
June 1, 2008 / Abe Pralle

Low-level coding part 1.1: Using ‘&’

Re: Geof’s comment on Part 1 – here’s some more detail on the “&” operator.

Say there were 4 variables:

int a;
int b;
int* ptr;
int** ptrptr;

and say those 4 variables lived at these 4 memory locations starting at 0x400:

0x400 [ (empty) ] a
0x404 [ (empty) ] b
0x408 [ (empty) ] ptr
0x40c [ (empty) ] ptrptr

Now let’s set a value for each of those variables:

a = 3;
b = 5;
ptr = &a;
ptrptr = &ptr;

The memory would now look like this:

0x400 [ 3 ] a
0x404 [ 5 ] b
0x408 [ 0x400 ] ptr
0x40c [ 0x408 ] ptrptr

Now let’s add 1 to ‘a’ using ‘ptr’:

(*ptr)++; // adds 1 to location 0x400 since the variable 'ptr' contains 0x400.

Now let’s set ‘ptr’ to point to ‘b’:

ptr++;  // using pointer arithmetic, 'ptr' goes from containing "0x400" to "0x404".

Now let’s print out the memory locations of all the variables:

cout << &a << endl << &b << endl << &ptr << endl << &ptrptr << endl;
// prints out:
//   0x400
//   0x404
//   0x408
//   0x40c
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: