t13APointersIntroduction Pps
t13APointersIntroduction Pps
CSCI 230
Pointers
Introduction
Dale Roberts, Lecturer
Computer Science, IUPUI
E-mail: [email protected]
Dale Roberts
What is Pointer
CS Dept.
Location A:
Highway Location C:
Bring your
Intersection Crabapple
money to
Tree
IUPUI SL-280
to exchange
Phone rings Find next hostage
and says message
Deliver on the top of
ransom to traffic light
I-65 and on Michigan
West St. St. and
intersection West St. Location D:
IUPUI SL-280
Find
Location B:
Instruction
Traffic Light
Under
The crabapple
tree next to old
law school
Hostage
CS A B C D
A pointer is an address.
Address of next
location
Dale Roberts
What is Pointer
Snoopy
Lucy knows Linus knows Charlie knows Snoopy knows Woodstock is with Snoopy
Sally knows
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 Snoopy
instance making a Linus Charlie
linus = &charlie;
/* linuss content is the info (pointer) to locate charlie, which is charlies address*/
Dale Roberts
Pointer Variable Declarations and Initialization
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-by-
reference 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
ptr x
x=10; FFFF
5000 10
ptr x
FFFF 10
ptr = &x; 5000 FFFF
Dale Roberts
Pointer Operators
&: Address Operator
Returns address of operand
yPtr y
int y = 5;
5
int *yPtr;
yPtr = &y;
/* yPtr points to y */
/* yPtr gets address of y */
yptr y
500000 600000 600000 5
Dale Roberts
Pointer Operators
* : Indirection / De-referencing Operator
Returns a synonym/alias of what its operand
points to
*yptr returns y (because yptr points to y)
* can be used for assignment that returns alias to
an object
*yptr = 7; // changes y to 7
Dereferenced pointer (operand of *) must be a
variable (no constants)
* and & are inverses
They cancel each other out
Dale Roberts
Pointer Operators
Example:
int i = 5;
int *pi;
pi = &i; /* place the address of i into pi */
Assume Symbol Table
variable address value at the address
pi i
i 874 5 902 874 874
5
pi 902 874
Dale Roberts
Example:
Variable Address Value at address
int i,*pi,**ppi;
i 100 5
i = 5;
pi 104 100
pi = &i;
ppi 108 104
ppi = π
ppi pi i
108 104 100
104 100 5