Beruflich Dokumente
Kultur Dokumente
CSCI 230
Pointers
Pointer Arithmetic
Dale Roberts, Lecturer
Computer Science, IUPUI
E-mail: droberts@cs.iupui.edu
Dale Roberts
++vPtr, vPtr++,
--vPtr, vPtr--
Dale Roberts
Example:
Five element int array on machine with 4 byte
ints
vPtr points to first element v[ 0 ]whose address
location is 3000 (vPtr = 3000)
vPtr += 2;
v[0] v[1]
Dale Roberts
v[2]
v[3]
v[4]
ppa
644 10
648 15
652
656
660
700
640
pa
Variable
Address
Value
640
644
10
648
15
pa
700
640
ppa
800
700
Questions:
Expression
Value
Note
pa+1
644
640+1*4
pa+3
652
640+3*4
pa+i
660
640+i*4
ppa+1
702
700+1*2
ppa+i
710
700+i*2
*pa+1
5+1
*(pa+1)
10
a[1]=pa[1]=*(a+1)
pa[2]
15
648
*ppa
640
value of pa
*ppa+1
644
pa+1
*(ppa+1)
invalid
*(702)
**ppa+1
a[0]+1 = 5+1
*(*ppa+1)
Dale Roberts
10
*(pa+1)=*(640+1*4)
Dale Roberts
bPtr = b;
//
//
bPtr = &b[ 0 ];
// Explicitly assigns bPtr to address of first element of b
To access element b[ 3 ]:
x=*( bPtr + 3 ) //
x=bptr[ 3 ]
//
x=*( b + 3 )
Dale Roberts
Dale Roberts
Arrays of Pointers
Arrays can contain pointers
For example: an array of strings
char *suit[4] = {"Hearts", "Diamonds",
"Clubs", "Spades"};
Strings are pointers to the first character
char * each element of suit is a pointer to a char
The strings are not actually stored in the array suit, only pointers to
the strings are stored
suit[0]
\0
suit[1]
suit[2]
\0
suit[3]
\0
\0
suit array has a fixed size, but strings can be of any size
Dale Roberts
Pointers to Functions
Pointer to function
Contains address of function
Similar to how array name is address of first
element
Function name is starting address of code
that defines function
Dale Roberts