Tom Kelliher, CS 220
Sept. 14, 2011
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> : <Sizeof> \n\n"); printf("offset: %X @ %X : %d\n", offset, &offset, sizeof(offset)); printf("base: %X @ %X : %d\n", base, &base, sizeof(base)); for (offset = 0; offset < 8; offset++) printf("A[%d]: %X @ %X : %d\n", offset, *(base + offset), base + offset, sizeof(*(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 -m32 -o baseOffset baseOffset.c
% ./baseOffset
Is memory word addressable or byte addressable?
Are the variables word-aligned?
offset
is incremented by one for each iteration of the
for
loop, yet the addresses of successive array elements differ
by four. Why is that?
base
and
the first element of the array?
% gcc -m64 -o baseOffset baseOffset.cRun the program. One of the
sizeof
values has changed. Can you
explain why that value has changed?