Pointers
Pointers
Pointers
Outline
• Introduction
• Pointer Variable Definitions and Initialization
• Pointer Operators
• Pointer expressions and arithmetic
Introduction
• Pointers
– Powerful, but difficult to master
– Simulate call-by-reference
– Close relationship with arrays and strings
Let’s look to something interesting
Which one to go and grab first?
Compare:
Address1 :: Address2 => Nearness
Value1 :: Value2 => Quantity
Assess:
Need of quickness or more food
Object1
Address1
Value1
Object2
Address2
Value2
Pointer Variable Definitions and
Initialization
• Pointer variables
– Contain memory addresses as their values
– Normal variables contain a specific value (direct
reference) count
7
y ypt y
r
5 50000 60000 60000 5
yPtr 0 0 0
Value of yptr
is the address
of y
Pointer Operators
• * (indirection/dereferencing operator)
– Returns the value of the variable that it points to.
– *yptr returns value of y (because yptr points to y)
– * can be used for assignment
*yptr = 7; /* changes y to 7 */
Example Code
This program
demonstrates
the use of the
pointer
operators: &
and *
Output
The address of a is 0012FF7C
The value of aPtr is 0012FF7C
The value of a is 7
The value of *aPtr is 7
Showing that * and & are complements of each other.
&*aPtr = 0012FF7C
*&aPtr = 0012FF7C
Pointer Expressions and Pointer
Arithmetic
• Arithmetic operations can be performed on
pointers
– Increment/decrement pointer (++ or --)
– Add an integer to a pointer( + or += , - or -=)
– Pointers may be subtracted from each other
• Operations are meaningless unless performed
on an array.
Pointer Expressions and Pointer
Arithmetic
• An array int v[5] has been defined on machine
with 2 byte integers.
– int *vPtr;
– vPtr = v;
– vPtr points to first element v[0]
• at location 3000 (vPtr = 3000)
– vPtr += 2; sets vPtr to 3004
• vPtr points to v[2] (incremented by 2), but the
machine has 2 byte ints, so it points to address 3004
getch();
}
Wild pointer
• Pointer which are not initialized during its
definition holding some junk value( a valid
address) are Wild pointer.
• Example of wild pointer:
int *ptr;