Every variable in a C program is stored somewhere in the memory of the
computer. And every location in memory has a unique address. Assume that a C
program contains the declarations
int x;
float y;
char z;
Here is a picture of a piece of the computer's memory.
|-------|
1000 | 17 | x Here, we have pictured ten memory
|-------| locations, with addresses ranging
1001 | 175.2 | y from 1000 to 1009. C has stored
|-------| the variable x (whose value is
1002 | 'x' | z currently 17) at location 1000,
|-------| the variable y at location 1001, and
1003 | | the variable z at location 1002.
|-------|
1004 | | We as programmers have no control
|-------| over where C stores a particular
1005 | | variable, but the location chosen
|-------| for a variable by C never changes.
1006 | |
|-------| Furthermore, we can easily find out
1007 | | where C has chosen to store a
|-------| variable, and then make use of that
1008 | | information
|-------|
1009 | |
|-------|
Actually, the picture above is a bit misleading. Why is that?
Click here for the answer
Although you haven't made much use of it, you already know how to find the
address of a variable in memory. How?
Click here for the answer
Given our picture above, what would be the values of &x, &y, &z?
Click here for the answer
An address into memory is represented as an unsigned integer, so they
can be printed out as unsigned integers. So it should be easy to
write a program to show us where C stores variables. Run ``ptr1.c''
in your ``examples'' directory (or view it directly). Do you see anything unexpected?
Click here for an answer
This is all very nice, but being able to print out the location in memory isn't
particularly interesting. In the next section, you'll start seeing what good
can come of knowing the address of a variable.
Hamlet Project
hamlet@cs.utah.edu