Tom Kelliher, CS 220
Sept. 16, 2009
A pointer is a typed variable that holds the memory address of a variable
of the appropriate type. The unary operator & returns the memory
address (location) of a variable. If i is of type int,
then &i is of type pointer to int.
The unary operator * (not to be confused with the binary
multiplication operator) has two context-dependent meanings:
* indicates that the variable's
type is pointer to some base type -- see the example below.
* ``dereferences'' a pointer variable,
chasing the memory address to the variable to which the pointer points.
Again, see the example below.
Note that if ip is type pointer to int then *ip is type
int. Thus, the * and & operators are inverses of each
other.
double x = 0.0;
double *dblPtr; /* pointer to double */
int i = 1;
int *intPtr; /* pointer to int */
int **intPtrPtr; /* pointer to pointer to int --- intPtrPtr hold the
* memory address of another pointer
*/
dblPtr = &x;
intPtr = &i;
intPtrPtr = &intPtr;
Given the example code above, what is the value of each of the following
expressions:
i, x.
&x
&i
&intPtr
dblPtr, *dblPtr.
intPtr, *intPtr.
intPtrPtr, *intPtrPtr, **intPtrPtr
Consider the following C program (available on the class web site
as baseoffset.c for copy & paste purposes):
#include <stdio.h>
int main()
{
int offset;
int *base;
int A[8] = { 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0 };
offset = 0;
base = &A[0];
printf("Legend:\n <Variable>: <Value> @ <Address>\n\n");
printf("offset: %X @ %X\n", offset, &offset);
printf("base: %X @ %X\n", base, &base);
for (offset = 0; offset < 8; offset++)
printf("A[%d]: %X @ %X\n", offset, *(base + offset), base + offset);
return 0;
}
for loop:
printf("A[%d]: %X @ %X\n", offset, *(base + offset), base + offset);
base? What type of data does it hold?
offset What type of data does it hold?
base + offset?
*(base + offset) and the expression base + offset?
% gcc -o baseOffset baseOffset.c
% ./baseOffset
Is memory word addressable or byte addressable?
Are the variables word-aligned?