Chapter 7

Pointers Explained

 

PROGRAM STATEMENTS

WHAT HAPPENS IN MEMORY

int *p;

 

Memory is allocated for a pointer to an integer named p – say at memory location 1200.

int num;

Memory is allocated for an integer variable named num – say at memory location 1800.

num=78;

The variable num is given the value of 78, which is stored at memory location 1800.

p=#

The pointer p is given the memory location of the variable num.  In our example this is 1800.

*p=24;

This statement gives the location pointed at by p(in our case location 1800, which is where num is stored) the value 24.  This changed the value of num to 24.

To Summarize:

&p – the address of p = 1200

p – the contents of p = 1800 (the location p points to)

*p – contents of memory location pointed to by p = 24

 

POINTER ANALOGY

 

The situation:

1.                You own a van and are interested in going into the business of renting it out to people that need it for moving.

2.                You keep the van at a remote location – like a variable stored in memory.

3.                You lease your van through a rental support agency that keeps a registry book of vehicles available for rent – like a pointer variable.

 

Steps you need to make your business work:

1.                Ask rental support agency to reserve a place in their registry book for you to write the address where your van is located – like declaring a pointer variable.

2.                Rent a remote location to store your van – like declaring an ordinary variable.

3.                Store your van at the location – give your ordinary variable a value.

4.                Give the rental agency the address of the van – like use the & operator and assigning the address of the ordinary variable to the pointer variable.

5.                Customers go to the address the rental agency gives them to get the van – like using the * operator with a pointer variable.

 

Return to 1336 Page