Last modified on 15 June 2014, at 13:54

Programming Concepts: Pointers

UNIT 3 - ⇑ Programming Concepts ⇑

← Object-oriented programming (OOP) Pointers Recursive Techniques →


Pointer a pointing to the memory address associated with variable b.

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.

Example: Pointers

Let's take a look at how pointers are used in the C programming Language.

We are going to deal with two variables:

a
ptr

We are also going to meet two key characters:

& - 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:

int a = 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.

Exercise: Pointers

Give a uses for pointers:

Answer :

storing next free memory addresses. Used to create abstract data types.

What would the following output, where cout << writes a line to the screen:

  1. int q = 89;
    
  2. int *next = NULL;
    
  3.  
    
  4. next = &q;
    
  5. cout << *next;
    
  6.  
    
  7. q = 23;
    
  8. *next = 56;
    
  9. cout << q;
    

Answer :

89

56