Académique Documents
Professionnel Documents
Culture Documents
Outline
7.1 Introduction
7.2 Pointer Variable Declarations and
Initialization
7.3 Pointer Operators
7.4 Calling Functions by Reference
7.5 Using the Const Qualifier with Pointers
7.6 Bubble Sort Using Call by Reference
7.7 Pointer Expressions and Pointer Arithmetic
• Pointers
– Powerful, but difficult to master
– Simulate call-by-reference
– Close relationship with arrays and strings
• Pointer declarations
– * used with pointer variables
int *myPtr;
– Declares a pointer to an int (pointer of type int *)
– Multiple pointers, multiple *
int *myPtr1, *myPtr2;
– Can declare pointers to any data type
– Initialize pointers to 0, NULL, or an address
• 0 or NULL - points to nothing (NULL preferred)
y yptr y
5 500000 600000 600000 5
yPtr
Address of y
is value of
yptr
The value of a is 7
The value of *aPtr is 7
Proving that * and & are complements of each other. Program Output
&*aPtr = 0012FF88
*&aPtr = 0012FF88
2000 Prentice Hall, Inc. All rights reserved.
7.4 Calling Functions by Reference
• Call by reference with pointer arguments
– Pass address of argument using & operator
– Allows you to change actual location in memory
– Arrays are not passed with & because the array name is already a
pointer
• * operator
– Used as alias/nickname for variable inside of function
void double(int *number)
{
*number = 2 * (*number);
}
*number used as nickname for the variable passed
FIG07_13.c:
Error E2024 FIG07_13.c 16: Cannot modify a const object in
function main
Program Output
*** 1 errors in Compile ***
• Psuedocode
Initialize array
print data in original order
Call function bubblesort
print sorted array
Define bubblesort
will print 40
• sizeof can be used with
– Variable names
– Type name
– Constant values
location
3000 3004 3008 3012 3016
• Subtracting pointers
– Returns number of elements from one to the other.
vPtr2 = v[2];
vPtr = v[0];
vPtr2 - vPtr == 2.
suit[1] ’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’\0’
Ace Two Three Four Five Six Seven Eight Nine Ten Jack Queen King
0 1 2 3 4 5 6 7 8 9 10 11 12
Hearts 0
Diamonds 1
Clubs 2
Spades 3
Clubs King
– The numbers 1-52 go into the array - this is the order they are dealt
First refinement
For each of the 52 cards While chosen slot of deck has been
previously chosen
Place card number in randomly Choose slot of deck randomly
Shuffle the deck selected unoccupied slot of deck Place card number in chosen slot of
deck
Deal 52 cards For each of the 52 cards For each slot of the deck array
66 { Outline
67 return b < a; /* swap if b is less than a */
68 }
3.1 Define
69 functions.
70 int descending( int a, int b )
71 {
73 }