Week 10 - Pointers
Week 10 - Pointers
Pointers
Dr. Ashfaq Hussain Farooqi
Introduction
● Pointers
○ Simulate pass-by-reference
2
Pointer Variable Declarations
and Initialization
● Pointer variables
○ Contain memory addresses as values
○ Normally, variable contains specific value (direct reference)
○ Pointers contain address of variable that has specific value (indirect reference)
● Indirection count
○ Referencing value through pointer 7
4
Pointer Operators
● & (address operator)
○ Returns memory address of its operand
○ Example
int y = 5;
int *yPtr;
yPtr = &y; // yPtr gets address of y
○ yPtr “points to” y
y yptr y
5 500000 600000 600000 5
yPtr
address of y
is value of
yptr
5
Pointer Operators
● * (indirection/dereferencing operator)
*yptr = 9; // assigns 9 to y
6
7
1 // Fig. 5.4: fig05_04.cpp Outline
2 // Using the & and * operators.
3 #include <iostream>
4 fig05_04.cpp
5 using std::cout;
(1 of 2)
6 using std::endl;
7
8 int main()
9 {
10 int a; // a is an integer
11 int *aPtr; // aPtr is a pointer to an integer
12
13 a = 7;
14 aPtr = &a; // aPtr assigned address of a
15
16 cout << "The address of a is " << &a
17 << "\nThe value of aPtr is " << aPtr;
18
19 cout << "\n\nThe value of a is " << a
20 << "\nThe value of *aPtr is " << *aPtr; * and & are inverses
21
of each other
22 cout << "\n\nShowing that * and & are inverses of "
23 << "each other.\n&*aPtr = " << &*aPtr
24 << "\n*&aPtr = " << *&aPtr << endl;
25
○ Pass-by-value
9
Calling Functions by Reference
● Pass-by-reference with pointer arguments
○ Simulate pass-by-reference
○ Arrays not passed with & because array name already pointer
10
11
1 // Fig. 5.6: fig05_06.cpp Outline
2 // Cube a variable using pass-by-value.
3 #include <iostream>
4 fig05_06.cpp
5 using std::cout;
(1 of 2)
6 using std::endl;
7
8 int cubeByValue( int ); // prototype
9
10 int main()
11 {
12 int number = 5;
13
14 cout << "The original value of number is " Pass number
<< number;by value; result
15 returned by
16 // pass number by value to cubeByValue cubeByValue
17 number = cubeByValue( number );
18
19 cout << "\nThe new value of number is " << number << endl;
20
21 return 0; // indicates successful termination
22
23 } // end main
24
15
16
1 // Fig. 5.10: fig05_10.cpp Outline
2 // Converting lowercase letters to uppercase letters
3 // using a non-constant pointer to non-constant data.
4 #include <iostream> fig05_10.cpp
5
(1 of 2)
6 using std::cout;
7 using std::endl;
Parameter is nonconstant
8
9 #include <cctype> // prototypes for islower and toupper pointer to nonconstant data
10
11 void convertToUppercase( char * );
12
13 int main()
14 {
15 char phrase[] = "characters and $32.98"; convertToUppercase
16 modifies variable phrase
17 cout << "The phrase before conversion is: " << phrase;
18 convertToUppercase( phrase );
19 cout << "\nThe phrase after conversion is: "
20 << phrase << endl;
21
22 return 0; // indicates successful termination
23
24 } // end main
25
21
22
1 // Fig. 5.13: fig05_13.cpp Outline
2 // Attempting to modify a constant pointer to
3 // non-constant data.
4 fig05_13.cpp
5 int main()
(1 of 1)
6 {
7 int x, y;
8 fig05_13.cpp
9 // ptr is
ptr is a constant pointer to an integer constant
that can pointer to output (1 of 1)
10 // integer.
be modified through ptr, but ptr always points to the
Can modify x (pointed to by
11 // same memory location.
ptr)
Cannotsince x not
modify constant.
ptr to point
12 int * const ptr = &x;
13 to new address since ptr is
14 *ptr = 7; // allowed: constant.
*ptr is not const
15 ptr = &y; // error: ptr is const; cannot assign new address
16 Line 15 generates compiler
17 return 0; // indicates successful error by attempting to assign
termination
18 new address to constant
19 } // end main pointer.
25
26
1 // Fig. 5.15: fig05_15.cpp Outline
2 // This program puts values into an array, sorts the values into
3 // ascending order, and prints the resulting array.
4 #include <iostream> fig05_15.cpp
5
(1 of 3)
6 using std::cout;
7 using std::endl;
8
9 #include <iomanip>
10
11 using std::setw;
12
13 void bubbleSort( int *, const int ); // prototype
14 void swap( int * const, int * const ); // prototype
15
16 int main()
17 {
18 const int arraySize = 10;
19 int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
20
21 cout << "Data items in original order\n";
22
23 for ( int i = 0; i < arraySize; i++ )
24 cout << setw( 4 ) << a[ i ];
25
int myArray[10];
will print 40
29
● sizeof can be used with
30
1 // Fig. 5.16: fig05_16.cpp Outline
2 // Sizeof operator when used on an array name
3 // returns the number of bytes in the array.
4 #include <iostream> fig05_16.cpp
5
(1 of 2)
6 using std::cout;
7 using std::endl;
8
9 size_t getSize( double * ); // prototype
10
11 int main()
12 {
13 double array[ 20 ]; Operator sizeof applied to
14
an array returns total number
15 cout << "The number of bytes in the array is "
of bytes in array.
16 << sizeof( array );
17
18 cout << "\nThe number of bytes returned by getSize is "
19 << getSize( array ) << endl;
20
21 return 0; // indicates successful termination
22
23 } // end main Function getSize returns
24 number of bytes used to store
array address.
vPtr points to v[ 2 ]
v[0] v[1] v[2] v[3] v[4]
35
Pointer Expressions and Pointer
Arithmetic
● Subtracting pointers
○ Returns number of elements between two addresses
vPtr2 = v[ 2 ];
vPtr = v[ 0 ];
vPtr2 - vPtr == 2
● Pointer assignment
○ Pointer can be assigned to another pointer if both of same type
○ If not same type, cast operator must be used
○ Exception: pointer to void (type void *)
■ Generic pointer, represents any type
■ No casting needed to convert pointer to void pointer
■ void pointers cannot be dereferenced
36
Pointer Expressions and Pointer
Arithmetic
● Pointer comparison
○ Example: could show that one pointer points to higher numbered element of array
than other pointer
37
Relationship Between Pointers
and
● ArraysArrays
and pointers closely related
○ Array name like constant pointer
○ Pointers can do array subscripting operations
● Accessing array elements with pointers
○ Element b[ n ] can be accessed by *( bPtr + n )
■ Called pointer/offset notation
○ Addresses
■ &b[ 3 ] same as bPtr + 3
○ Array name can be treated as pointer
■ b[ 3 ] same as *( b + 3 )
○ Pointers can be subscripted (pointer/subscript notation)
■ bPtr[ 3 ] same as b[ 3 ]
38
39
1 // Fig. 5.20: fig05_20.cpp Outline
2 // Using subscripting and pointer notations with arrays.
3
4 #include <iostream> fig05_20.cpp
5
(1 of 2)
6 using std::cout;
7 using std::endl;
8
9 int main()
10 {
11 int b[] = { 10, 20, 30, 40 };
12 int *bPtr = b; // set bPtr to point to array b
13
14 // output array b using array subscript notation
15 cout << "Array b printed with:\n"
16 << "Array subscript notation\n"; Using array subscript
17 notation.
18 for ( int i = 0; i < 4; i++ )
19 cout << "b[" << i << "] = " << b[ i ] << '\n';
20
21 // output array b using the array name and
22 // pointer/offset notation
23 cout << "\nPointer/offset notation where "
24 << "the pointer is the array name\n";
25
Pointer/offset notation
*(bPtr + 0) = 10
*(bPtr + 1) = 20
*(bPtr + 2) = 30
*(bPtr + 3) = 40
suit[1] ’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’\0’
○ suit array has fixed size, but strings can be of any size
44
Case Study: Card Shuffling and
Dealing Simulation
● Card shuffling program
○ Use an array of pointers to strings, to store suit names
○ Use a double scripted array (suit by value)
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
○ Place 1-52 into the array to specify the order in which the cards are dealt
45
Case Study: Card Shuffling and
Dealing Simulation
● Pseudocode for shuffling and dealing
simulation Third refinement
For each of the 52 cards For each slot of the deck array
Deal 52 cards
Find card number in deck array and print If slot contains card number
face and suit of card Print the face and suit of the card
46
47
1 // Fig. 5.24: fig05_24.cpp Outline
2 // Card shuffling dealing program.
3 #include <iostream>
4 fig05_24.cpp
5 using std::cout;
(1 of 4)
6 using std::left;
7 using std::right;
8
9 #include <iomanip>
10
11 using std::setw;
12
13 #include <cstdlib> // prototypes for rand and srand
14 #include <ctime> // prototype for time
15
16 // prototypes
17 void shuffle( int [][ 13 ] );
18 void deal( const int [][ 13 ], const char *[], const char *[] );
19
20 int main() suit array contains pointers
21 {
to char arrays.
22 // initialize suit array
23 const char *suit[ 4 ] =
24 { "Hearts", "Diamonds", "Clubs", "Spades" };
25
52
Function Pointers
● Calling functions using pointers
○ Assume parameter:
■ bool ( *compare ) ( int, int )
○ Execute function with either
■ ( *compare ) ( int1, int2 )
● Dereference pointer to function to execute
OR
■ compare( int1, int2 )
● Could be confusing
○ User may think compare name of actual function in program
53
54
1 // Fig. 5.25: fig05_25.cpp Outline
2 // Multipurpose sorting program using function pointers.
3 #include <iostream>
4 fig05_25.cpp
5 using std::cout;
(1 of 5)
6 using std::cin;
7 using std::endl;
8
9 #include <iomanip>
10
11 using std::setw; Parameter is pointer to
12 function that receives two
13 // prototypes integer parameters and
14 void bubble( int [], const int, bool (*)( int, int ) ); returns bool result.
15 void swap( int * const, int * const );
16 bool ascending( int, int );
17 bool descending( int, int );
18
19 int main()
20 {
21 const int arraySize = 10;
22 int order;
23 int counter;
24 int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
25
○ Menu-driven systems
■ All functions must have same return type and same parameter types
59
60
1 // Fig. 5.26: fig05_26.cpp Outline
2 // Demonstrating an array of pointers to functions.
3 #include <iostream>
4 fig05_26.cpp
5 using std::cout;
(1 of 3)
6 using std::cin;
7 using std::endl;
8
9 // function prototypes
10 void function1( int );
11 void function2( int );
12 void function3( int );
13
14 int main()
15 { Array initialized with names
16 of three functions;
// initialize array of 3 pointers to functions that each function
17 // take an int argument and return void names are pointers.
18 void (*f[ 3 ])( int ) = { function1, function2, function3 };
19
20 int choice;
21
22 cout << "Enter a number between 0 and 2, 3 to end: ";
23 cin >> choice;
24
63
Fundamentals of Characters
and
● StringStrings
assignment
○ Character array
■ char color[] = "blue";
● Creates 5 element char array color
○ last element is '\0'
○ Variable of type char *
■ char *colorPtr = "blue";
● Creates pointer colorPtr to letter b in string “blue”
○ “blue” somewhere in memory
○ Alternative for character array
■ char color[] = { ‘b’, ‘l’, ‘u’, ‘e’, ‘\0’ };
64
Fundamentals of Characters
and Strings
● Reading strings
○ Assign input to character array word[ 20 ]
65
Fundamentals of Characters
and Strings
● cin.getline
○ Read line of text
○ cin.getline( array, size, delimiter );
○ Copies input into specified array until either
■ One less than size is reached
■ delimiter character is input
○ Example
char sentence[ 80 ];
cin.getline( sentence, 80, '\n' );
66
String Manipulation Functions
of the String-handling Library
● String handling library <cstring> provides functions to
○ Compare strings
67
String Manipulation Functions of
the String-handling Library
char *strcpy( char *s1, const Copies the string s2 into the character
char *s2 ); array s1. The value of s1 is returned.
char *strncpy( char *s1, const Copies at most n characters of the string s2
char *s2, size_t n ); into the character array s1. The value of s1 is
returned.
char *strcat( char *s1, const Appends the string s2 to the string s1. The
char *s2 ); first character of s2 overwrites the terminating
null character of s1. The value of s1 is
returned.
char *strncat( char *s1, const Appends at most n characters of string s2 to
char *s2, size_t n ); string s1. The first character of s2 overwrites
the terminating null character of s1. The value
of s1 is returned.
int strcmp( const char *s1, Compares the string s1 with the string s2. The
const char *s2 ); function returns a value of zero, less than zero
or greater than zero if s1 is equal to, less than
or greater than s2, respectively.
68
String Manipulation Functions of
the String-handling Library
int strncmp( const char *s1, const Compares up to n characters of the string
char *s2, size_t n ); s1 with the string s2. The function returns
zero, less than zero or greater than zero if
s1 is equal to, less than or greater than s2,
respectively.
char *strtok( char *s1, const char A sequence of calls to strtok breaks
*s2 ); string s1 into “tokens”—logical pieces
such as words in a line of text—delimited
by characters contained in string s2. The
first call contains s1 as the first argument,
and subsequent calls to continue tokenizing
the same string contain NULL as the first
argument. A pointer to the current token is
returned by each call. If there are no more
tokens when the function is called, NULL is
returned.
70