Académique Documents
Professionnel Documents
Culture Documents
CSCI 230
Pointers
Introduction
Dale Roberts, Lecturer
Computer Science, IUPUI
E-mail: droberts@cs.iupui.edu
Dale Roberts
What is Pointer
CS Dept.
Location A:
Highway
Intersection
Location C:
Crabapple
Tree
Find next
message
on the top of
traffic light
on Michigan
St. and
West St.
Phone rings
and says
Deliver
ransom to
I-65 and
West St.
intersection
Location B:
Traffic Light
CS
Find
Instruction
Under
The crabapple
tree next to old
law school
Bring your
money to
IUPUI SL-280
to exchange
hostage
Location D:
IUPUI SL-280
Hostage
A pointer is an address.
Address of next
location
Dale Roberts
What is Pointer
Example: Find out who is with Woodstock
Pig Pen
Sally
Lucy
Lucy knows
Sally knows
Linus
Woodstock
Snoopy
Linus knows Charlie knows Snoopy knows Woodstock is with Snoopy
Pig Pen points to Lucy; Lucy points to Sally; Sally points to Linus;
Linus points to Charlie; Charlie points to Snoopy;
Snoopy has Woodstock
An instance uses a
pointer to link to a next
Linus
instance making a
chain.
Dale Roberts
Charlie
Snoopy
Pointer declarations:
datatype snoopy, *charlie, **linus;
snoopy =
; /* snoopys content is Woodstock */
charlie = &snoopy;
/* charlies content is the info (pointer) to locate snoopy, which is snoopys address*/
linus = &charlie;
/* linuss content is the info (pointer) to locate charlie, which is charlies address*/
Pointers
Definition:
A pointer is a variable that contains address of
another variable.
A powerful feature of C, but difficult to master
Pointers enable programs to simulate call-byreference and create/manipulate dynamic data
structures
Close relationship with arrays and strings
Dale Roberts
Pointer variables
Contain memory addresses as their values
Normal variables contain a specific value (direct reference)
count
7
Pointers contain address of a variable that has a specific
value (indirect reference)
countPtr count
7
Indirection referencing a pointer value
Dale Roberts
int *myPtr;
Declares a pointer to an int (pointer of type int *)
Multiple pointers require using a * before each variable
declaration
Can declare pointers to any data type
Example:
int *ptr, x;
5000
x=10;
5000
ptr
ptr
FFFF
FFFF
ptr
ptr = &x;
5000 FFFF
Dale Roberts
FFFF
x
10
x
10
Pointer Operators
Dale Roberts
Pointer Operators
Pointer Operators
Example:
int i = 5;
int *pi;
pi = &i; /* place the address of i into pi */
Assume Symbol Table
variable
address
874
pi
902
874
pi
902 874
// same as i = 5;
*pi = *pi * 2;
// same as i = i * 2;
*pi *= 2;
// same as i *= 2;
Dale Roberts
874
i
5
Example:
int i,*pi,**ppi;
i = 5;
pi = &i;
ppi = π
108
ppi
104
104
Variable
Address
Value at address
100
pi
104
100
ppi
108
104
pi
100
100
i
5
Usage
Meaning
Value
pi
address of int
100
*pi
int value
&pi
address of pointer
104
ppi
address of pointer
104
*ppi
address of int
100
**ppi
int value
Dale Roberts