Download as pdf or txt
Download as pdf or txt
You are on page 1of 143

C++ How to Program,

Late Objects Version, 7/e

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.


 This chapter explains basic pointer concepts and rein-
forces the intimate relationship among arrays and
pointers.
 Pointers also enable pass-by-reference and can be
used to create and manipulate dynamic data
structures that can grow and shrink, such as linked
lists, queues, stacks and trees.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 A pointer contains the memory address of a variable
that, in turn, contains a specific value.
 In this sense, a variable name directly references a
value, and a pointer indirectly references a value.
 Referencing a value through a pointer is called
indirection.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
Include Ptr in a pointer’s name
makes the code easier to read
 The declaration
 int *countPtr, count;
declares the variable countPtr to be of type int * (i.e., a pointer
to an int value) and is read (right to left), “countPtr is a pointer
to int.”
◦ Variable count in the preceding declaration is declared to be an int, not
a pointer to an int.
◦ The * in the declaration applies only to countPtr.
◦ Each variable being declared as a pointer must be preceded by an
asterisk (*).
 Pointers can be declared to point to objects of any data type.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 Pointers should be initialized either when they’re
declared or in an assignment.
 A pointer may be initialized to 0, NULL or an address
of the corresponding type.
◦ Such pointers are called null pointers.
◦ NULL is equivalent to 0, but in C++, 0 is used by convention.
◦ The value 0 is the only integer value that can be assigned
directly to a pointer variable

int *countPtr = NULL, count;

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 The address operator (&) is a unary operator that obtains
the memory address of its operand.
 Assuming the declarations
 int y = 5; // declare variable y
int *yPtr; // declare pointer variable yPtr
the statement
 yPtr = &y; // assign address of y to yPtr
assigns the address of the variable y to pointer variable yPtr.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
• Figure 7.3 shows another pointer representation in
memory with integer variable y stored at memory
location 600000 and pointer variable yPtr stored at
memory location 500000.
• The operand of the address operator must be an
lvalue
• The address operator cannot be applied to constants
or to expressions that do not result in references.
 An lvalue (locator value) represents an object
that occupies some identifiable location in
memory (i.e. has an address)
 An rvalue is an expression that does not
represent an object occupying some
identifiable location in memory
 Examples:
int x = 6;
int y = 5; // declare variable y
int *yPtr; // declare pointer variable yPtr
yPtr = &y; // ???
yPtr = &(x+y); // ???
© 1992-2011 by Pearson Education,
Inc. All Rights Reserved.
 The * operator (known as the indirection operator or
dereferencing operator), returns a synonym for the object
to which its pointer operand points.
 A dereferenced pointer may also be used on the left side
of an assignment.

int y = 5; // declare variable y


int *yPtr; // declare pointer variable yPtr
yPtr = &y; // assign address of y to yPtr
*yPtr = 6;
int x = *yPtr;

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
int y = 5; // declare variable y
int *yPtr; // declare pointer variable yPtr
*yPtr = 6; // ???
• Causes exceptions
• Or result in unexpected results
int y = 5; // declare variable y
*y = 6; // ???
int *yPtr = NULL;
*yPtr = 6; // ???

• Causes run-time error


int y = 5; // declare variable y
int *yPtr; // declare pointer variable yPtr
yPtr = &y; // assign address of y to yPtr
cout << yPtr; // ???
• Output format is compiler dependent…
 The & and * operators are inverses of one another.
 Figure 7.5 lists the precedence and associativity of the
operators introduced to this point.
 The address (&) and dereferencing operator (*) are
unary operators on the third level.
int y = 5; // declare variable y
int *yPtr; // declare pointer variable yPtr
yPtr = &*&y; // assign address of y to yPtr
cout << yPtr;// output format is compiler dependent

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
// address of a = 0x0012F580

© 1992-2011 by Pearson Education,


Inc. All Rights Reserved.
 There are three ways in C++ to pass arguments to a
function:
◦ pass-by-value
◦ pass-by-reference with reference arguments
◦ pass-by-reference with pointer arguments
 Pointers, like references, can be used to modify one or
more variables in the caller or to pass pointers to large
data objects to avoid the overhead of passing the objects
by value.
 In C++, you can use pointers and the indirection operator
(*) to accomplish pass-by-reference.
© 1992-2011 by Pearson Education, Inc.
All Rights Reserved.
 Figure 7.7 passes the variable number to function
cubeByReference using pass-by-reference with a
pointer argument—the address of number is passed to
the function.
 The function dereferences the pointer and cubes the
value to which nPtr points.
◦ This directly changes the value of number in main.
 Figures 7.8–7.9 analyze graphically the execution of the
programs in Fig. 7.6 and Fig. 7.7, respectively.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 In the function header and in the prototype for a function
that expects a one-dimensional array as an argument,
pointer notation may be used.
 The compiler does not differentiate between a function
that receives a pointer and a function that receives a one-
dimensional array.
◦ The function must “know” when it’s receiving an array or simply a
single variable which is being passed by reference.
 When the compiler encounters a function parameter for a
one-dimensional array of the form int b[], the compiler
converts the parameter to the pointer notation int *b.
◦ Both forms are interchangeable.
© 1992-2011 by Pearson Education, Inc.
All Rights Reserved.
 A reference is a name constant for an address.
 Once a reference is established to a variable, you
cannot change the reference to reference another
variable
 To get the value pointed to by a pointer, you need to
use the dereferencing operator *
 To assign an address of a variable into a pointer, you
need to use the address-of operator &

© 1992-2011 by Pearson Education,


Inc. All Rights Reserved.
 On the other hand, referencing and dereferencing are
done on the references implicitly
 No explicit dereferencing operator * should be used.
 Furthermore, to assign an address of a variable to a
reference variable, no address-of operator & is
needed.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
int number1 = 88, number2 = 22;

// Create a pointer pointing to number1


int *pNumber1 = &number1; // Explicit referencing
*pNumber1 = 99; // Explicit dereferencing
cout << *pNumber1 << endl;
cout << &number1 << endl; What are the outputs of these four
cout << pNumber1 << endl; statements?
cout << &pNumber1 << endl;
pNumber1 = &number2;

© 1992-2011 by Pearson Education,


Inc. All Rights Reserved.
// Create a reference to number1
int &refNumber1 = number1;
refNumber1 = 11;
cout << refNumber1 << endl;
What are the outputs of these
cout << &number1 << endl;
statements?
cout << &refNumber1 << endl;
refNumber1 = &number2;
Is this ok?
refNumber1 = number2;
number2++;
cout << refNumber1 << endl;
cout << number1 << endl; What are the outputs of these
cout << number2 << endl; statements?

© 1992-2011 by Pearson Education,


Inc. All Rights Reserved.
 Many possibilities exist for using (or not using) const
with function parameters.
 Principle of least privilege
◦ Always give a function enough access to the data in its
parameters to accomplish its specified task, but no more.
◦ If a value does not change in the body of a function to which
it’s passed, make it a const

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 There are four ways to pass a pointer to a function
1. a nonconstant pointer to nonconstant data
2. a nonconstant pointer to constant data (Fig. 7.10)
3. a constant pointer to nonconstant data (Fig. 7.11)
4. a constant pointer to constant data (Fig. 7.12)
 Each combination provides a different level of access
privilege.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 The highest access is granted by a nonconstant pointer
to nonconstant data
◦ The data can be modified through the dereferenced pointer,
and the pointer can be modified to point to other data.
 Such a pointer’s declaration (e.g., int *countPtr) does
not include const.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 A nonconstant pointer to constant data
◦ The pointer can be modified, but the data to which it points cannot be
modified
◦ Any attempt to modify the data is a compilation error
 Example usage: receive an array argument to a function that will
process each array element, but should not be allowed to modify
the data.
 Sample declaration:
 const int *countPtr;
 Read from right to left as “countPtr is a pointer to an
integer constant.”

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
Figure 7.10 demonstrates the compilation error messages
produced when attempting to compile a function that
receives a nonconstant pointer to constant data, then tries to
use that pointer to modify the data.
 A constant pointer to non-constant data is a pointer
that always points to the same memory location; the data at
that location can be modified through the pointer.
 An example of such a pointer is an array name
 A constant pointer to non-constant data can be used to receive
an array as an argument to a function that accesses array
elements using array subscript notation.
 Pointers that are declared const must be initialized when
they’re declared.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 The minimum access privilege is granted by a constant
pointer to constant data.
 Such a pointer always points to the same
memory location, and the data at that location
cannot be modified via the pointer.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
This declaration is
read from right to left
as “ptr is a constant
pointer to an integer
constant.”
char A_char = ‘A’;
char *myPtr = &A_char;

 Consider the following three declarations.


What is the difference between each of them?

const char *myPtr = &char_A;


char *const myPtr = &char_A;
const char * const myPtr = &char_A;

© 1992-2011 by Pearson Education,


Inc. All Rights Reserved.
const char *myPtr = &char_A;

Declares a pointer to a constant character. You cannot


use this pointer to change the value being pointed to

© 1992-2011 by Pearson Education,


Inc. All Rights Reserved.
char *const myPtr = &char_A;

Declares a constant pointer to a character. The location


stored in the pointer cannot change. You cannot
change where this pointer point
char char_A = 'A';
char char_B = 'B';

char * const myPtr = &char_A;


myPtr = &char_B; // error - can't change address of myPtr

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
const char * const myPtr = &char_A;

Declares a pointer to a character where both the


pointer value and the value being pointed at will not
change

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 Selection sort
◦ The first iteration of the algorithm selects the smallest
element in the array and swaps it with the first element.
◦ The second iteration selects the second-smallest element
(which is the smallest element of the remaining elements) and
swaps it with the second element.
◦ The algorithm continues until the last iteration selects the
second-largest element and swaps it with the second-to-last
index, leaving the largest element in the last index.
◦ After the ith iteration, the smallest i items of the array will be
sorted into increasing order in the first i elements of the array.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
i = 0 min = 2

7 3 1 9 23 18 16

© 1992-2011 by Pearson Education,


Inc. All Rights Reserved.
i = 0 min = 2

1 3 7 9 23 18 16
i = 1 min = 1

1 3 7 9 23 18 16
i = 1 min = 1

1 3 7 9 23 18 16
i = 2 min = 2

1 3 7 9 23 18 16
i = 2 min = 2

1 3 7 9 23 18 16
i = 3 min = 3

1 3 7 9 23 18 16
i = 3 min = 3

1 3 7 9 23 18 16
i=4 min = 6

1 3 7 9 23 18 16
i=4 min = 6

1 3 7 9 16 18 23
i=5 min = 5

1 3 7 9 16 18 23
Selection Sort on Youtube
 The unary operator sizeof determines the size of an
array (or of any other data type, variable or constant)
in bytes during program compilation.
 When applied to the name of an array, the sizeof
operator returns the total number of bytes in the array
as a value of type size_t.
 When applied to a pointer parameter in a function that
receives an array as an argument, the sizeof operator
returns the size of the pointer in bytes—not the size of
the array
© 1992-2011 by Pearson Education, Inc.
All Rights Reserved.
double = 8 bytes
 The number of elements in an array also can be
determined using the results of two sizeof operations.
 Consider the following array declaration:
 double realArray[ 22 ];
 To determine the number of elements in the array, the
following expression (which is evaluated at compile time)
can be used:
 sizeof realArray / sizeof( realArray[0] )

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 Operator sizeof can be applied to any expression or
type name.
 When sizeof is applied to a variable name (which is not
an array name) or other expression, the number of
bytes used to store the specific type of the expression’s
value is returned.
 The parentheses used with sizeof are required only if
a type name is supplied as its operand.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
sizeof int; // ERROR
 cout<<sizeof(string*)<<endl;
 cout<<sizeof(int*)<<endl;
 cout<<sizeof(char****)<<endl;

Assuming the size of a pointer variable is 4


bytes…

© 1992-2011 by Pearson Education,


Inc. All Rights Reserved.
char a[] = “abcdef”;
int b[20] = {3,4};
char c[2][3] = {“aa”, “bb”};

1. cout << sizeof(a) << endl;


2. cout << sizeof(b) << endl;
3. cout << sizeof(c) << endl;

© 1992-2011 by Pearson Education,


Inc. All Rights Reserved.
 Pointers are valid operands in arithmetic expressions,
assignment expressions and comparison expressions.
 pointer arithmetic—certain arithmetic operations may
be performed on pointers:
◦ increment (++)
◦ decremented (--)
◦ an integer may be added to a pointer (+ or +=)
◦ an integer may be subtracted from a pointer (- or -=)
◦ one pointer may be subtracted from another of the same
type
© 1992-2011 by Pearson Education, Inc.
All Rights Reserved.
 Assume that array int v[5] has been declared and that
its first element is at memory location 3000.
 Assume that pointer vPtr has been initialized to point
to v[0] (i.e., the value of vPtr is 3000).
 Figure 7.16 diagrams this situation for a machine with
four-byte integers.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 In conventional arithmetic, the addition 3000 + 2 yields
the value 3002.
◦ This is normally not the case with pointer arithmetic.
◦ When an integer is added to, or subtracted from, a pointer,
the pointer is not simply incremented or decremented by
that integer, but by that integer times the size of the object
to which the pointer refers.
◦ The number of bytes depends on the object’s data type.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
Continue on the previous example, what is the
output of the following statements (assuming
vPtr is currently pointing at 3008)?
1. cout << vPtr++ << endl;
2. cout << vPtr-- << endl;
3. cout << vPtr+2 << endl;
4. cout << vPtr-1 << endl;

© 1992-2011 by Pearson Education,


Inc. All Rights Reserved.
char x = ‘a’; // addr of x = 3000
int y = 5; // addr of y = 4000
double z = 6.0; // addr of z = 5000

1. cout << &x+1 << endl;


2. cout << &y+1 << endl;
3. cout << &z+1 << endl;

Assume the sizes of char/int/double are 1/4/8

© 1992-2011 by Pearson Education,


Inc. All Rights Reserved.
int y; // declare variable y
int *yPtr = &y; // declare pointer yPtr
*(yPtr+2) = 6; // ???
int x[5],y[5]; // declare array x and y
int *xPtr = x; // declare pointer xPtr
int *yPtr = y; // declare pointer yPtr
*(yPtr+xPtr) = 6; // ???
*(yPtr-xPtr) = 6; // ???
int y[5]; // declare array y
int *yPtr = y; // declare pointer yPtr
*(y+5) = 6; // ???
 Pointer variables pointing to the same array may be
subtracted from one another.
 For example, if vPtr contains the address 3000 and
v2Ptr contains the address 3008, the statement
 x = v2Ptr - vPtr; // =???
 would assign to x the number of array elements from
vPtr to v2Ptr—in this case, 2.
 Pointer arithmetic is meaningless unless performed on
a pointer that points to an array.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 A pointer can be assigned to another pointer if both
pointers are of the same type.
 Otherwise, a cast operator (normally a
reinterpret_cast; discussed in Section 17.8) must be
used
◦ Exception to this rule is the pointer to void (i.e., void *).
 All pointer types can be assigned to a pointer of type
void * without casting.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
int y; // declare variable y
double *yPtr = &y; // Compiler ERROR!!
 void pointers are pointers that point to a value that
has no type
 This gives void pointers a great flexibility, by being
able to point to any data type, from an integer
value or a float to a string of characters

int y; // declare variable y


double *yPtr = &y; // Compiler ERROR!!
void *vPtr = &y; // OK!!

Note: All operations on void pointers are compilation errors


except comparison

© 1992-2011 by Pearson Education,


Inc. All Rights Reserved.
 A void * pointer cannot be dereferenced.
◦ The compiler must know the data type to determine the
number of bytes to be dereferenced for a particular

int y; // declare variable y


void *yPtr = &y; // OK
*yPtr = 2; // Not OK!!!
*(int*)yPtr = 2; // OK!!!

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
int y; // declare variable y
void *yPtr = &y; // OK
cout << yPtr + 1 << endl; // ???

• You’ll get a compile warning


• yPtr will be literally incremented by 1 (may
be compiler dependent)

© 1992-2011 by Pearson Education,


Inc. All Rights Reserved.
 Pointers can be compared using equality and
relational operators.
◦ Comparisons using relational operators are meaningless
unless the pointers point to members of the same array.
◦ Pointer comparisons compare the addresses stored in the
pointers.
 A common use of pointer comparison is determining
whether a pointer is 0 (i.e., the pointer is a null
pointer—it does not point to anything).

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 An array name can be thought of as a constant pointer.
 Pointers can be used to do any operation involving array
subscripting.
 Assume the following declarations:
 int b[ 5 ]; // create 5-element int array b
int *bPtr; // create int pointer bPtr
 Because the array name (without a subscript) is a
(constant) pointer to the first element of the array, we can
set bPtr to the address of the first element in array b with
the statement
 bPtr = b; // assign address of array b to bPtr
 equivalent to
 bPtr = &b[ 0 ]; // also assigns address of array b
// to bPtr
© 1992-2011 by Pearson Education, Inc.
All Rights Reserved.
 Array element b[ 3 ] can alternatively be referenced
with the pointer expression
 *( bPtr + 3 )

 The 3 in the preceding expression is the offset to the


pointer.
 This notation is referred to as pointer/offset notation.
◦ Note: The parentheses are necessary, because the
precedence of * is higher than that of +.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 Just as the array element can be referenced with a pointer
expression, the address
 &b[ 3 ]
 can be written with the pointer expression
 bPtr + 3
 The array name (which is implicitly const) can be treated
as a pointer and used in pointer arithmetic.
 For example, the expression
 *( b + 3 )
 also refers to the array element b[ 3 ].
 In general, all subscripted array expressions can be written
with a pointer and an offset.
© 1992-2011 by Pearson Education, Inc.
All Rights Reserved.
Following the previous example, which one of
the followings are correct / incorrect?
 b++
 bPtr++
 b+3
 bPtr+3

© 1992-2011 by Pearson Education,


Inc. All Rights Reserved.
 Pointers can be subscripted exactly as arrays can.
 For example, the expression
 bPtr[ 1 ]

 refers to the array element b[ 1 ]; this expression uses


pointer/subscript notation.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 This section introduces C-style, pointer-based strings.
 C++’s string class is preferred for use in new programs,
because it eliminates many of the security problems
that can be caused by manipulating C strings.
 We cover C strings here for a deeper understanding of
arrays.
 Also, if you work with legacy C++ programs, you may
be required to manipulate these pointer-based strings.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 Characters are the fundamental building blocks of C++ source
programs.
 Character constant
◦ An integer value represented as a character in single quotes.
◦ The value of a character constant is the integer value of the character in
the machine’s character set.
 A string is a series of characters treated as a single unit.
◦ May include letters, digits and various special characters such as +, -, *,
/and $.
 String literals, or string constants, in C++ are written in double
quotation marks
 A pointer-based string is an array of characters ending with a
null character ('\0').
 A string is accessed via a pointer to its first character.
© 1992-2011 by Pearson Education, Inc.
All Rights Reserved.
 The value of a string literal is the address of its first character,
but the sizeof a string literal is the length of the string including
the terminating null character.
 A string literal may be used as an initializer in the declaration of
either a character array or a variable of type char *.
 String literals have static storage class (they exist for the
duration of the program) and may or may not be shared if the
same string literal is referenced from multiple locations in a
program.
 The effect modifying a string literal is undefined; thus, you
should always declare a pointer to a string literal as const char *.
 When declaring a character array to contain a string, the array
must be large enough to store the string and its terminating null
character.
© 1992-2011 by Pearson Education, Inc.
All Rights Reserved.
 Because a string is an array of characters, we can
access individual characters in a string directly with
array subscript notation.
 A string can be read into a character array using stream
extraction with cin.
 The setw stream manipulator can be used to ensure
that the string read into word does not exceed the size
of the array.
◦ Applies only to the next value being input.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 In some cases, it’s desirable to input an entire line of text
into a character array.
 For this purpose, the cin object provides the member
function getline.
 Three arguments — a character array in which the line of
text will be stored, a length and a delimiter character.
 The function stops reading characters when the delimiter
character '\n' is encountered, when the end-of-file
indicator is entered or when the number of characters
read so far is one less than the length specified in the
second argument.
 The third argument to cin.getline has '\n' as a default
value.
© 1992-2011 by Pearson Education, Inc.
All Rights Reserved.
 A character array representing a null-terminated string
can be output with cout and <<.
 The characters of the string are output until a
terminating null character is encountered; the null
character is not printed.
 cin and cout assume that character arrays should be
processed as strings terminated by null characters

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
char name[15];
cin >> setw(sizeof name) >> name; // OK
cin.getline(name, sizeof name); // OK
cin >> name; // NOT OK

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 Arrays may contain pointers.
 A common use of such a data structure is to form an array
of pointer-based strings, referred to simply as a string array.
 Each entry in the array is a string, but in C++ a string is
essentially a pointer to its first character, so each entry in
an array of strings is simply a pointer to the first character
of a string.
 const char * const suit[ 4 ] =
{ "Hearts", "Diamonds",
"Clubs", "Spades" };
◦ An array of four elements.
◦ Each element is of type “pointer to char constant data.”
© 1992-2011 by Pearson Education, Inc.
All Rights Reserved.
What is the output of the following statement?

const char * const suit[ 4 ] =


{ "Hearts", "Diamonds",
"Clubs", "Spades" };

cout << sizeof(suit) << endl;

© 1992-2011 by Pearson Education,


Inc. All Rights Reserved.
 String arrays are commonly used with command-line
arguments that are passed to function main when a
program begins execution.
 Such arguments follow the program name when a
program is executed from the command line.
 A typical use of command-line arguments is to pass
options to a program.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
int main (int argc, char* argv[]) {

}

 argc: number of command line arguments,


including the program name
 argv: argument strings

© 1992-2011 by Pearson Education,


Inc. All Rights Reserved.
 A pointer to a function contains the function’s address
in memory.
◦ A function’s name is actually the starting address in memory
of the code that performs the function’s task.
 Pointers to functions can be
◦ Passed to functions
◦ Returned from functions
◦ Stored in arrays
◦ Assigned to other function pointers
◦ Used to call the underlying function
© 1992-2011 by Pearson Education, Inc.
All Rights Reserved.
 To illustrate the use of pointers to functions, Fig. 7.20
modifies the selection sort program of Fig. 7.13.
 Function selectionSort receives a pointer to a
function—either function ascending or function
descending—as an argument in addition to the integer
array to sort and the size of the array.
 Functions ascending and descending determine the
sorting order.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 bool ( *compare )( int, int )
 This parameter specifies a pointer to a function.
◦ The keyword bool indicates that the function being pointed to
returns a bool value.
◦ The text (*compare) indicates the name of the pointer to the
function (the * indicates that parameter compare is a pointer).
◦ The text (int, int) indicates that the function pointed to by compare
takes two integer arguments.
◦ Parentheses are needed around *compare to indicate that compare
is a pointer to a function.
 The corresponding parameter in the function prototype of
selectionSort is
 bool (*)( int, int )
© 1992-2011 by Pearson Education, Inc.
All Rights Reserved.
 The function passed to selectionSort is called as follows:
 ( *compare )( work[ smallestOrLargest ],
work[ index ] )
 Just as a pointer to a variable is dereferenced to access the value
of the variable, a pointer to a function is dereferenced to
execute the function.
 The parentheses around *compare are necessary; otherwise,
the * operator would attempt to dereference the value returned
from the function call.
 Call could have been made without dereferencing the pointer, as
in
 compare(work[smallestOrLargest], work[index])

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 Given the previous selection sort
implementation, how can we make it sort
numbers like this: 2,4,6,8,7,5,3,1?
 In other words, even numbers must precede
odd numbers, and they must be in
ascending/descending orders respectively.

© 1992-2011 by Pearson Education,


Inc. All Rights Reserved.
 Arrays of pointers to functions
 Menu-driven systems
 Pointers to each function stored in array of pointers to functions
All functions must have same return type and same parameter types
 Menu choice determines subscript into array of function pointers

137
1 // Fig. 8.29: fig08_29.cpp
2 // Demonstrating an array of pointers to functions.
3 #include <iostream>
4 using std::cout;
5 using std::cin; fig08_29.cpp
6 using std::endl;
7 (1 of 3)
8 // function prototypes -- each function performs similar actions
9 void function0( int );
10 void function1( int );
11 void function2( int );
12
13 int main()
14 {
15 // initialize array of 3 pointers to functions that each
16 // take an int argument and return void
17 void (*f[ 3 ])( int ) = { function0, function1, function2 };
18
19 int choice; Array initialized with names
20 of three functions
21 cout << "Enter a number between 0 and 2, 3 to end: ";
22 cin >> choice;

138
23
24 // process user's choice
25 while ( ( choice >= 0 ) && ( choice < 3 ) )
26 {
27 // invoke the function at location choice in
fig08_29.cpp
28 // the array f and pass choice as an argument
29 (*f[ choice ])( choice );
(2 of 3)
30
31 cout << "Enter a number between 0 and 2, 3 to end: ";
Call chosen function by dereferencing
32 cin >> choice;
corresponding element in array
33 } // end while
34
35 cout << "Program execution completed." << endl;
36 return 0; // indicates successful termination
37 } // end main
38
39 void function0( int a )
40 {
41 cout << "You entered " << a << " so function0 was called\n\n";
42 } // end function function0
43
44 void function1( int b )
45 {
46 cout << "You entered " << b << " so function1 was called\n\n";
47 } // end function function1

139
48
49 void function2( int c )
50 {
51 cout << "You entered " << c << " so function2 was called\n\n";
52 } // end function function2
fig08_29.cpp
Enter a number between 0 and 2, 3 to end: 0
You entered 0 so function0 was called
(3 of 3)
Enter a number between 0 and 2, 3 to end: 1
You entered 1 so function1 was called

Enter a number between 0 and 2, 3 to end: 2


You entered 2 so function2 was called

Enter a number between 0 and 2, 3 to end: 3


Program execution completed.

140
 Modify the selectionSort example using array
of function pointers

© 1992-2011 by Pearson Education,


Inc. All Rights Reserved.
 You can provide an initializer for a newly created
fundamental-type variable, as in
 double *ptr = new double( 3.14159 );
 The same syntax can be used to specify a comma-
separated list of arguments to the constructor of an
object.
 To deallocate a dynamically allocated memory, use the
statement
 delete ptr;
© 1992-2011 by Pearson Education, Inc.
All Rights Reserved.
 You can also use the new operator to allocate arrays
dynamically.
 int *gradesArray = new int[ 10 ];
 A dynamically allocated array’s size can be specified using
any non-negative integral expression that can be evaluated
at execution time.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 To deallocate a dynamically allocated array, use the
statement
 delete [] ptr;
 If the pointer points to an array of objects, the
statement first calls the destructor for every object in
the array, then deallocates the memory.
 Using delete on a null pointer (i.e., a pointer with the
value 0) has no effect.

© 1992-2011 by Pearson Education, Inc.


All Rights Reserved.
 How can we dynamically create a two
dimensional integer array of size 100x100
using the new operator?

© 1992-2011 by Pearson Education,


Inc. All Rights Reserved.

You might also like