A pointer is a data type whose value refers directly to (or "points to") another value stored elsewhere in the computer memory using its address.

Pointers are incredibly important computing concepts as we need pointers to create many of the ADTs (Abstract Data Types) we are going to talk about. Some languages don't allow you to directly manipulate them, but all languages use them. For this section of the book you need to be familiar with the concept of pointers as we'll be using them heavily when we talk about linked lists, queues and stacks.

Quick examples of pointers might include the next free memory location in an array, or the location in memory that an array is stored at.

& - where &a would return the address location of variable a* - where *ptr = 8 means follow the memory address stored in ptr and set that location to 8

Assume that a is located at address 0x8130 in memory and ptr at 0x8134; also assume this is a 32-bit machine such that an int is 32-bits in size. The following is what would be in memory after the following code snippet is executed:

inta=5;int*ptr=NULL;

Address

Contents

0x8130

0x00000005

0x8134

0x00000000

(The NULL pointer shown here is 0x00000000.) By assigning the address of a to ptr:

ptr=&a;

yields the following memory values:

Address

Contents

0x8130

0x00000005

0x8134

0x00008130

Then by dereferencing ptr by coding:

*ptr=8;

the computer will take the contents of ptr (which is 0x8130), 'locate' that address, and assign 8 to that location yielding the following memory:

Address

Contents

0x8130

0x00000008

0x8134

0x00008130

Clearly, accessing a will yield the value of 8 because the previous instruction modified the contents of a by way of the pointer ptr.