Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
13 views77 pages

Pointers

The document provides an overview of pointers in programming, detailing their declarations, initialization, and usage in functions for pass-by-reference. It covers pointer operators, common programming errors, and best practices for using pointers, including the importance of initializing pointers and using the const qualifier. Additionally, it includes examples of passing arguments by value and by reference using pointers, along with tips for error prevention and portability considerations.

Uploaded by

bqwks69852
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views77 pages

Pointers

The document provides an overview of pointers in programming, detailing their declarations, initialization, and usage in functions for pass-by-reference. It covers pointer operators, common programming errors, and best practices for using pointers, including the importance of initializing pointers and using the const qualifier. Additionally, it includes examples of passing arguments by value and by reference using pointers, along with tips for error prevention and portability considerations.

Uploaded by

bqwks69852
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

1

Pointers

 2006 Pearson Education, Inc. All rights reserved.


2

8.1 Introduction

• Pointers
– Powerful, but difficult to master
– Can be used to perform pass-by-reference
– Can be used to create and manipulate dynamic data
structures
– Close relationship with arrays and strings
• char * pointer-based strings

 2006 Pearson Education, Inc. All rights reserved.


3
8.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
– Referencing value through pointer

 2006 Pearson Education, Inc. All rights reserved.


4
8.2 Pointer Variable Declarations and
Initialization (Cont.)
• Pointer declarations
– * indicates variable is a pointer
• Example
– int *myPtr;
• Declares pointer to int, of type int *
• Multiple pointers require multiple asterisks
int *myPtr1, *myPtr2;
• Pointer initialization
– Initialized to 0, NULL, or an address
• 0 or NULL points to nothing (null pointer)

 2006 Pearson Education, Inc. All rights reserved.


5

Common Programming Error 8.1

Assuming that the * used to declare a pointer


distributes to all variable names in a declaration’s
comma-separated list of variables can lead to
errors. Each pointer must be declared with the *
prefixed to the name (either with or without a
space in between—the compiler ignores the space).
Declaring only one variable per declaration helps
avoid these types of errors and improves program
readability.

 2006 Pearson Education, Inc. All rights reserved.


6

Good Programming Practice 8.1

Although it is not a requirement, including the


letters Ptr in pointer variable names makes it
clear that these variables are pointers and that
they must be handled appropriately.

 2006 Pearson Education, Inc. All rights reserved.


7

Fig. 8.1 | Directly and indirectly referencing a variable.

 2006 Pearson Education, Inc. All rights reserved.


8

Error-Prevention Tip 8.1

Initialize pointers to prevent pointing to


unknown or uninitialized areas of memory.

 2006 Pearson Education, Inc. All rights reserved.


9

8.3 Pointer Operators

• Address operator (&)


– Returns memory address of its operand
– Example
• int y = 5;
int *yPtr;
yPtr = &y;
assigns the address of variable y to pointer variable yPtr
– Variable yPtr “points to” y
• yPtr indirectly references variable y’s value

 2006 Pearson Education, Inc. All rights reserved.


10

Fig. 8.2 | Graphical representation of a pointer pointing to a variable in memory.

 2006 Pearson Education, Inc. All rights reserved.


11

8.3 Pointer Operators (Cont.)

•* operator
– Also called indirection operator or dereferencing operator
– Returns synonym for the object its operand points to
– *yPtr returns y (because yPtr points to y)
– Dereferenced pointer is an lvalue
*yptr = 9;
•* and & are inverses of each other
– Will “cancel one another out” when applied consecutively
in either order

 2006 Pearson Education, Inc. All rights reserved.


12

Fig. 8.3 | Representation of y and yPtr in memory.

 2006 Pearson Education, Inc. All rights reserved.


13

Common Programming Error 8.2

Dereferencing a pointer that has not been


properly initialized or that has not been
assigned to point to a specific location in
memory could cause a fatal execution-time
error, or it could accidentally modify
important data and allow the program to
run to completion, possibly with incorrect
results.

 2006 Pearson Education, Inc. All rights reserved.


14

Common Programming Error 8.3

An attempt to dereference a variable that is not


a pointer is a compilation error.

 2006 Pearson Education, Inc. All rights reserved.


15

Common Programming Error 8.4

Dereferencing a null pointer is normally


a fatal execution-time error.

 2006 Pearson Education, Inc. All rights reserved.


16

Portability Tip 8.1

The format in which a pointer is output is


compiler dependent. Some systems output
pointer values as hexadecimal integers,
while others use decimal integers.

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 8.4: fig08_04.cpp 17
2 // Using the & and * operators. Outline
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 fig08_04.cpp
7 int main()
8 { (1 of 2)
9 int a; // a is an integer
10 int *aPtr; // aPtr is an int * -- pointer to an integer
11 Variable aPtr is
12 a = 7; // assigned 7 to a a point to an int
13 aPtr = &a; // assign the address of a to aPtr

Initialize aPtr with the


address of variable a

 2006 Pearson Education,


Inc. All rights reserved.
14 18
15 cout << "The address of a is " << &a Address of a and the value
Outline
16 << "\nThe value of aPtr is " << aPtr; of aPtr are identical
17 cout << "\n\nThe value of a is " << a
18 << "\nThe value of *aPtr is " << *aPtr; Value of a and the dereferenced
19 cout << "\n\nShowing that * and & are inverses of " fig08_04.cpp
aPtr are identical
20 << "each other.\n&*aPtr = " << &*aPtr
21 << "\n*&aPtr = " << *&aPtr << endl; * and & are inverses(2 of 2)
22 return 0; // indicates successful termination of each other
23 } // end main

The address of a is 0012F580


The value of aPtr is 0012F580

The value of a is 7
The value of *aPtr is 7

Showing that * and & are inverses of each other.


&*aPtr = 0012F580 * and & are inverses;same result
*&aPtr = 0012F580
when both are applied to aPtr

 2006 Pearson Education,


Inc. All rights reserved.
19

Operators Associativity Type

() [] left to right highest


++ -- static_cast< type >( operand ) left to right unary (postfix)
++ -- + - ! & * right to left unary (prefix)
* / % left to right multiplicative
+ - left to right additive
<< >> left to right insertion/extraction
< <= > >= left to right relational
== != left to right equality
&& left to right logical AND
|| left to right logical OR
?: right to left conditional
= += -= *= /= %= right to left assignment
, left to right comma

Fig. 8.5 | Operator precedence and associativity.

 2006 Pearson Education, Inc. All rights reserved.


20
8.4 Passing Arguments to Functions by
Reference with Pointers
• Three ways to pass arguments to a function
– Pass-by-value
– Pass-by-reference with reference arguments
– Pass-by-reference with pointer arguments
• A function can return only one value
• Arguments passed to a function using reference
arguments
– Function can modify original values of arguments
• More than one value “returned”

 2006 Pearson Education, Inc. All rights reserved.


21
8.4 Passing Arguments to Functions by
Reference with Pointers (Cont.)
• Pass-by-reference with pointer arguments
– Simulates pass-by-reference
• Use pointers and indirection operator
– Pass address of argument using & operator
– Arrays not passed with & because array name is already a
pointer
– * operator used as alias/nickname for variable inside of
function

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 8.6: fig08_06.cpp 22
2 // Cube a variable using pass-by-value. Outline
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 fig08_06.cpp
7 int cubeByValue( int ); // prototype
8 (1 of 1)
9 int main()
10 {
11 int number = 5;
12 Pass number by value; result
13 cout << "The original value of number is " << returned by cubeByValue
number;
14
15 number = cubeByValue( number ); // pass number by value to cubeByValue
16 cout << "\nThe new value of number is " << number << endl;
17 return 0; // indicates successful termination
18 } // end main
19 cubeByValue receives
20 // calculate and return cube of parameter passed-by-value
integer argument
21 int cubeByValue( int n ) Cubes local variable n
22 { and return the result
23 return n * n * n; // cube local variable n and return result
24 } // end function cubeByValue

The original value of number is 5


The new value of number is 125

 2006 Pearson Education,


Inc. All rights reserved.
23

Common Programming Error 8.5

Not dereferencing a pointer when it is necessary


to do so to obtain the value to which the pointer
points is an error.

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 8.7: fig08_07.cpp 24
2 // Cube a variable using pass-by-reference with a pointer argument. Outline
3 #include <iostream>
4 using std::cout; Prototype indicates parameter
5 using std::endl; is a pointer to an int
6 fig08_07.cpp
7 void cubeByReference( int * ); // prototype
8 (1 of 1)
9 int main()
10 {
11 int number = 5;
12 Apply address operator & to
13 cout << "The original value of number is " pass address of number to
<< number;
14 cubeByReference
15 cubeByReference( &number ); // pass number address to cubeByReference
16
17 cout << "\nThe new value of number is " << number << endl;
18 return 0; // indicates successful termination cubeByReference
19 } // end main modifies variable number
20
Modify and access int
21 // calculate cube of *nPtr; modifies variable number in main
22 void cubeByReference( int *nPtr )
variable using indirection
23 {
operator *
24 *nPtr = *nPtr * *nPtr * *nPtr; // cube *nPtr cubeByReference receives
25 } // end function cubeByReference address of an int variable,
i.e., a pointer to an int
The original value of number is 5
The new value of number is 125

 2006 Pearson Education,


Inc. All rights reserved.
25

Fig. 8.8 | Pass-by-value analysis of the program of Fig. 8.6.

 2006 Pearson Education, Inc. All rights reserved.


26

Fig. 8.9 | Pass-by-reference analysis (with a pointer argument) of the program of Fig. 8.7.

 2006 Pearson Education, Inc. All rights reserved.


27

8.5 Using const with Pointers

•const qualifier
– Indicates that value of variable should not be modified
– const used when function does not need to change the
variable’s value
• Principle of least privilege
– Award function enough access to accomplish task, but no
more
– Example
• A function that prints the elements of an array, takes array
and int indicating length
– Array contents are not changed – should be const
– Array length is not changed – should be const

 2006 Pearson Education, Inc. All rights reserved.


28

Portability Tip 8.2

Although const is well defined in ANSI C


and C++, some compilers do not enforce it
properly. So a good rule is, “Know your
compiler.”

 2006 Pearson Education, Inc. All rights reserved.


29

Error-Prevention Tip 8.2

Before using a function, check its function


prototype to determine the parameters that
it can modify.

 2006 Pearson Education, Inc. All rights reserved.


30

8.5 Using const with Pointers (Cont.)

• Four ways to pass pointer to function


– Nonconstant pointer to nonconstant data
• Highest amount of access
• Data can be modified through the dereferenced pointer
• Pointer can be modified to point to other data
– Pointer arithmetic
• Operator ++ moves array pointer to the next element
• Its declaration does not include const qualifier

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 8.10: fig08_10.cpp
31
2 // Converting lowercase letters to uppercase letters
3 // using a non-constant pointer to non-constant data.
Outline
4 #include <iostream>
5 using std::cout;
6 using std::endl;
fig08_10.cpp
7
8 #include <cctype> // prototypes for islower and toupper
Parameter is a nonconstant (1 of 2)
9 using std::islower;
10 using std::toupper;
pointer to nonconstant data
11
12 void convertToUppercase( char * );
13
14 int main()
15 {
16 char phrase[] = "characters and $32.98";
convertToUppercase
17 modifies variable phrase
18 cout << "The phrase before conversion is: " << phrase;
19 convertToUppercase( phrase );
20 cout << "\nThe phrase after conversion is: " << phrase << endl;
21 return 0; // indicates successful termination
22 } // end main

 2006 Pearson Education,


Inc. All rights reserved.
23 32
24 // convert string to uppercase letters Outline
Parameter sPtr is a nonconstant
25 void convertToUppercase( char *sPtr )
pointer to nonconstant data
26 {
27 while ( *sPtr != '\0' ) // loop while current character is not '\0'
28 {
Function islower returns true fig08_10.cpp
29 if ( islower( *sPtr ) ) // if character is lowercase,
if the character is lowercase (2 of 2)
30 *sPtr = toupper( *sPtr ); // convert to uppercase
31
32
Function toupper returns corresponding
sPtr++; // move sPtr to next character in string
33 } // end while uppercase character if original character is
34 } // end function convertToUppercase lowercase; otherwise toupper returns
the original character
The phrase before conversion is: characters and $32.98
The phrase after conversion is: CHARACTERS AND $32.98

Modify the memory address stored in sPtr


to point to the next element of the array

 2006 Pearson Education,


Inc. All rights reserved.
33

8.5 Using const with Pointers (Cont.)

• Four ways to pass pointer to function (Cont.)


– Nonconstant pointer to constant data
• Pointer can be modified to point to any appropriate data item
• Data cannot be modified through this pointer
• Provides the performance of pass-by-reference and the
protection of pass-by-value

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 8.11: fig08_11.cpp 34
2 // Printing a string one character at a time using
3 // a non-constant pointer to constant data.
Outline
4 #include <iostream>
Parameter is a nonconstant
5 using std::cout;
6 using std::endl;
pointer to constant data
fig08_11.cpp
7
8 void printCharacters( const char * ); // print using pointer to const data
9
(1 of 1)
10 int main()
11 {
12
Pass pointer phrase to function
const char phrase[] = "print characters of a string";
13 printCharacters
14 cout << "The string is:\n";
15 printCharacters( phrase ); // print characters in phrase
16 cout << endl;
17 return 0; // indicates successful termination
sPtr is a nonconstant pointer to constant data;
18 } // end main
19
it cannot modify the character to which it points
20 // sPtr can be modified, but it cannot modify the character to which
21 // it points, i.e., sPtr is a "read-only" pointer
22 void printCharacters( const char *sPtr )
23 {
Increment sPtr to point to the next character
24 for ( ; *sPtr != '\0'; sPtr++ ) // no initialization
25 cout << *sPtr; // display character without modification
26 } // end function printCharacters

The string is:


print characters of a string

 2006 Pearson Education,


Inc. All rights reserved.
1 // Fig. 8.12: fig08_12.cpp
35
2 // Attempting to modify data through a
3 // non-constant pointer to constant data.
Outline
4
5 void f( const int * ); // prototype
6
fig08_12.cpp
7 int main()
8 {
Parameter is a nonconstant (1 of 2)
9 int y;
10
pointer to constant data
11 f( &y ); // f attempts illegal modification
12 return 0; // indicates successful termination
13 } // end main Pass the address of int variable y
to attempt an illegal modification

 2006 Pearson Education,


Inc. All rights reserved.
14
36
15 // xPtr cannot modify the value of constant variable to which it points
16 void f( const int *xPtr )
Outline
17 {
18 *xPtr = 100; // error: cannot modify a const object
19 } // end function f
Attempt to modify a const fig08_12.cpp
Borland C++ command-line compiler error message:
object pointed to by xPtr
Error E2024 fig08_12.cpp 18:
(2 of 2)
Cannot modify a const object in function f(const int *)

Microsoft Visual C++ compiler error message:

c:\cpphtp5_examples\ch08\Fig08_12\fig08_12.cpp(18) : Error produced when


error C2166: l-value specifies const object
attempting to compile
GNU C++ compiler error message:

fig08_12.cpp: In function `void f(const int*)':


fig08_12.cpp:18: error: assignment of read-only location

 2006 Pearson Education,


Inc. All rights reserved.
37

Performance Tip 8.1

If they do not need to be modified by the called


function, pass large objects using pointers to
constant data or references to constant data, to
obtain the performance benefits of pass-by-
reference.

 2006 Pearson Education, Inc. All rights reserved.


38

Software Engineering Observation 8.3

Pass large objects using pointers to constant


data, or references to constant data, to obtain
the security of pass-by-value.

 2006 Pearson Education, Inc. All rights reserved.


39

8.5 Using const with Pointers (Cont.)

• Four ways to pass pointer to function (Cont.)


– Constant pointer to nonconstant data
• Always points to the same memory location
– Can only access other elements using subscript notation
• Data can be modified through the pointer
• Default for an array name
– Can be used by a function to receive an array argument
• Must be initialized when declared

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 8.13: fig08_13.cpp
40
2 // Attempting to modify a constant pointer to non-constant data.
3
Outline
4 int main()
5 {
6 int x, y;
fig08_13.cpp
7
8 ptr can
// ptr is a constant pointer to an integer that is a constant pointer to an integer
9 // be modified through ptr, but ptr always points to the
(1 of 1)
10 // same memory location.
11 int * const ptr = &x; // const pointer must be Can modify x (pointed to by
initialized
12
ptr) since x is not constant
13 *ptr = 7; // allowed: *ptr is not const
14 ptr = &y; // error: ptr is const; cannot assign to it a new address
15 return 0; // indicates successful termination
16 } // end main Cannot modify ptr to point to a
Borland C++ command-line compiler error message: new address since ptr is constant
Error E2024 fig08_13.cpp 14: Cannot modify a const object in function main()s

Microsoft Visual C++ compiler error message:


Line 14 generates a compiler
c:\cpphtp5e_examples\ch08\Fig08_13\fig08_13.cpp(14) : error C2166: error by attempting to assign
l-value specifies const object
a new address to a constant
GNU C++ compiler error message: pointer
fig08_13.cpp: In function `int main()':
fig08_13.cpp:14: error: assignment of read-only variable `ptr'

 2006 Pearson Education,


Inc. All rights reserved.
41

Common Programming Error 8.6

Not initializing a pointer that is declared


const is a compilation error.

 2006 Pearson Education, Inc. All rights reserved.


42

8.5 Using const with Pointers (Cont.)

• Four ways to pass pointer to function (Cont.)


– Constant pointer to constant data
• Least amount of access
• Always points to the same memory location
• Data cannot be modified using this pointer

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 8.14: fig08_14.cpp 43
2 // Attempting to modify a constant pointer to constant data. Outline
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 fig08_14.cpp
7 int main()
8 { (1 of 2)
9 int x = 5, y;
10
11 // ptr is a constant pointer to a constant integer.
12 // ptr always points to the same location; the integer
13 // at that location cannot be modified. ptr is a constant pointer
14 const int *const ptr = &x; to a constant integer
15
16 cout << *ptr << endl; Cannot modify x (pointed to by
17 ptr) since *ptr is constant
18 *ptr = 7; // error: *ptr is const; cannot assign new value
19 ptr = &y; // error: ptr is const; cannot assign new address
20 return 0; // indicates successful termination
21 } // end main

Cannot modify ptr to point to a


new address since ptr is constant

 2006 Pearson Education,


Inc. All rights reserved.
Borland C++ command-line compiler error message: 44
Error E2024 fig08_14.cpp 18: Cannot modify a const object in function main()
Outline
Error E2024 fig08_14.cpp 19: Cannot modify a const object in function main()

Microsoft Visual C++ compiler error message:


Line 18 generates a compiler
fig08_14.cpp
c:\cpphtp5e_examples\ch08\Fig08_14\fig08_14.cpp(18) : error C2166:
Lineby
error 19attempting
generates atocompiler
modify
l-value specifies const object aerror by attempting
constant of 2) to assign
object
(2
c:\cpphtp5e_examples\ch08\Fig08_14\fig08_14.cpp(19) : error C2166:
l-value specifies const object a new address to a constant
pointer
GNU C++ compiler error message:

fig08_14.cpp: In function `int main()':


fig08_14.cpp:18: error: assignment of read-only location
fig08_14.cpp:19: error: assignment of read-only variable `ptr'

 2006 Pearson Education,


Inc. All rights reserved.
45

8.7 sizeof Operators


• sizeof operator
– Returns size of operand in bytes
– For arrays, sizeof returns
( size of 1 element ) * ( number of elements )
– If sizeof( int ) returns 4 then
int myArray[ 10 ];
cout << sizeof( myArray );
will print 40
– Can be used with
• Variable names
• Type names
• Constant values

 2006 Pearson Education, Inc. All rights reserved.


46

Common Programming Error 8.7

Using the sizeof operator in a function to


find the size in bytes of an array parameter
results in the size in bytes of a pointer, not the
size in bytes of the array.

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 8.16: fig08_16.cpp
47
2 // Sizeof operator when used on an array name
3 // returns the number of bytes in the array.
Outline
4 #include <iostream>
5 using std::cout;
6 using std::endl;
fig08_16.cpp
7
8 size_t getSize( double * ); // prototype
9
(1 of 1)
10 int main()
11 {
12 double array[ 20 ]; // 20 doubles; occupies 160 bytes on our system
13
14 cout << "The number of bytes in the array is " << sizeof( array );
15
16 cout << "\nThe number of bytes returned by getSize is "
17 << getSize( array ) << endl; Operator sizeof applied to an array
18 return 0; // indicates successful termination returns total number of bytes in the array
19 } // end main
20
21 // return size of ptr
Function getSize returns the number
22 size_t getSize( double *ptr )
23 {
of bytes used to store array address
24 return sizeof( ptr );
25 } // end function getSize

The number of bytes in the array is 160 Operator sizeof returns


The number of bytes returned by getSize is 4
number of bytes of pointer

 2006 Pearson Education,


Inc. All rights reserved.
48

8.7 sizeof Operators (Cont.)


• sizeof operator (Cont.)
– Is performed at compiler-time
– For double realArray[ 22 ];
• Use sizeof realArray / sizeof( double ) to calculate
the number of elements in realArray
– Parentheses are only required if the operand is a type name

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 8.17: fig08_17.cpp 49
2 // Demonstrating the sizeof operator. Outline
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 fig08_17.cpp
7 int main()
8 { (1 of 2)
9 char c; // variable of type char
10 short s; // variable of type short
11 int i; // variable of type int
12 long l; // variable of type long
13 float f; // variable of type float
14 double d; // variable of type double
15 long double ld; // variable of type long double
16 int array[ 20 ]; // array of int
17 int *ptr = array; // variable of type int *

 2006 Pearson Education,


Inc. All rights reserved.
18
50
19 cout << "sizeof c = " << sizeof c Operator sizeof can be Outline
20 << "\tsizeof(char) = " << sizeof( char )
used on a variable name
21 << "\nsizeof s = " << sizeof s
22 << "\tsizeof(short) = " << sizeof( short )
23 << "\nsizeof i = " << sizeof i
24 << "\tsizeof(int) = " << sizeof( int ) Operator sizeoffig08_17.cpp
can be
25 << "\nsizeof l = " << sizeof l used on a type name
(2 of 2)
26 << "\tsizeof(long) = " << sizeof( long )
27 << "\nsizeof f = " << sizeof f
28 << "\tsizeof(float) = " << sizeof( float )
29 << "\nsizeof d = " << sizeof d
30 << "\tsizeof(double) = " << sizeof( double )
31 << "\nsizeof ld = " << sizeof ld
32 << "\tsizeof(long double) = " << sizeof( long double )
33 << "\nsizeof array = " << sizeof array
34 << "\nsizeof ptr = " << sizeof ptr << endl;
35 return 0; // indicates successful termination
36 } // end main

sizeof c = 1 sizeof(char) = 1
sizeof s = 2 sizeof(short) = 2
sizeof i = 4 sizeof(int) = 4
sizeof l = 4 sizeof(long) = 4
sizeof f = 4 sizeof(float) = 4
sizeof d = 8 sizeof(double) = 8
sizeof ld = 8 sizeof(long double) = 8
sizeof array = 80
sizeof ptr = 4 Operator sizeof returns the total
number of bytes in the array

 2006 Pearson Education,


Inc. All rights reserved.
51

Portability Tip 8.3

The number of bytes used to store a particular


data type may vary between systems. When
writing programs that depend on data type sizes,
and that will run on several computer systems,
use sizeof to determine the number of bytes
used to store the data types.

 2006 Pearson Education, Inc. All rights reserved.


52

Common Programming Error 8.8

Omitting the parentheses in a sizeof operation


when the operand is a type name is a compilation
error.

 2006 Pearson Education, Inc. All rights reserved.


53

Performance Tip 8.2

Because sizeof is a compile-time unary


operator, not an execution-time operator,
using sizeof does not negatively impact
execution performance.

 2006 Pearson Education, Inc. All rights reserved.


54

Error-Prevention Tip 8.3

To avoid errors associated with omitting the


parentheses around the operand of operator
sizeof, many programmers include
parentheses around every sizeof operand.

 2006 Pearson Education, Inc. All rights reserved.


55
8.8 Pointer Expressions and Pointer
Arithmetic
• Pointer arithmetic
– Increment/decrement pointer (++ or --)
– Add/subtract an integer to/from a pointer (+ or +=,
- or -=)
– Pointers may be subtracted from each other
– Pointer arithmetic is meaningless unless performed on a
pointer to an array

 2006 Pearson Education, Inc. All rights reserved.


56
8.8 Pointer Expressions and Pointer
Arithmetic (Cont.)
• 5 element int array on a machine using 4 byte
ints
– vPtr points to first element v[ 0 ], at location 3000
vPtr = &v[ 0 ];
– vPtr += 2; sets vPtr to 3008 (3000 + 2 * 4)
vPtr points to v[ 2 ]
• Subtracting pointers
– Returns number of elements between two addresses
vPtr2 = v[ 2 ];
vPtr = v[ 0 ];
vPtr2 - vPtr is 2

 2006 Pearson Education, Inc. All rights reserved.


57

Portability Tip 8.4

Most computers today have two-byte or four-


byte integers. Some of the newer machines
use eight-byte integers. Because the results of
pointer arithmetic depend on the size of the
objects a pointer points to, pointer arithmetic
is machine dependent.

 2006 Pearson Education, Inc. All rights reserved.


58

Fig. 8.18 | Array v and a pointer variable vPtr that points to v.

 2006 Pearson Education, Inc. All rights reserved.


59

Fig. 8.19 | Pointer vPtr after pointer arithmetic.

 2006 Pearson Education, Inc. All rights reserved.


60

Common Programming Error 8.9

Using pointer arithmetic on a pointer


that does not refer to an array of values
is a logic error.

 2006 Pearson Education, Inc. All rights reserved.


61

Common Programming Error 8.10

Subtracting or comparing two pointers


that do not refer to elements of the same
array is a logic error.

 2006 Pearson Education, Inc. All rights reserved.


62

Common Programming Error 8.11

Using pointer arithmetic to increment or


decrement a pointer such that the pointer
refers to an element past the end of the
array or before the beginning of the array
is normally a logic error.

 2006 Pearson Education, Inc. All rights reserved.


63
8.8 Pointer Expressions and Pointer
Arithmetic (Cont.)
• Pointer assignment
– Pointer can be assigned to another pointer if both are 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 *
• Casting is needed to convert void * to any other
type
• void pointers cannot be dereferenced

 2006 Pearson Education, Inc. All rights reserved.


64

Common Programming Error 8.12

Assigning a pointer of one type to a pointer


of another (other than void *) without
casting the first pointer to the type of the
second pointer is a compilation error.

 2006 Pearson Education, Inc. All rights reserved.


65

Common Programming Error 8.13

All operations on a void * pointer are


compilation errors, except comparing void *
pointers with other pointers, casting void *
pointers to valid pointer types and assigning
addresses to void * pointers.

 2006 Pearson Education, Inc. All rights reserved.


66
8.8 Pointer Expressions and Pointer
Arithmetic (Cont.)
• Pointer comparison
– Use equality and relational operators
– Compare addresses stored in pointers
• Comparisons are meaningless unless pointers point to
members of the same array
– Example
• Could show that one pointer points to higher-index element
of array than another pointer
– Commonly used to determine whether pointer is 0 (null
pointer)

 2006 Pearson Education, Inc. All rights reserved.


67
8.9 Relationship Between Pointers and
Arrays
• Arrays and pointers are closely related
– Array name is like constant pointer
– Pointers can do array subscripting operations

 2006 Pearson Education, Inc. All rights reserved.


68
8.9 Relationship Between Pointers and
Arrays (Cont.)
• Accessing array elements with pointers
– Assume declarations:
int b[ 5 ];
int *bPtr;
bPtr = b;
– Element b[ n ] can be accessed by *( bPtr + n )
• Called pointer/offset notation
– Addresses
• &b[ 3 ] is same as bPtr + 3
– Array name can be treated as pointer
• b[ 3 ] is same as *( b + 3 )
– Pointers can be subscripted (pointer/subscript notation)
• bPtr[ 3 ] is same as b[ 3 ]

 2006 Pearson Education, Inc. All rights reserved.


69

Common Programming Error 8.14

Although array names are pointers to the


beginning of the array and pointers can be
modified in arithmetic expressions, array names
cannot be modified in arithmetic expressions,
because array names are constant pointers.

 2006 Pearson Education, Inc. All rights reserved.


70

Good Programming Practice 8.2

For clarity, use array notation instead of pointer


notation when manipulating arrays.

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 8.20: fig08_20.cpp
71
2 // Using subscripting and pointer notations with arrays.
3 #include <iostream>
Outline
4 using std::cout;
5 using std::endl;
6
fig08_20.cpp
7 int main()
8 {
9 int b[] = { 10, 20, 30, 40 }; // create 4-element array b
(1 of 3)
10 int *bPtr = b; // set bPtr to point to array b
11
12 // output array b using array subscript notation
Using array subscript notation
13 cout << "Array b printed with:\n\nArray subscript notation\n";
14
15 for ( int i = 0; i < 4; i++ )
16 cout << "b[" << i << "] = " << b[ i ] << '\n';
17
18 // output array b using the array name and pointer/offset notation
19 cout << "\nPointer/offset notation where "
Usingarray name and
20 << "the pointer is the array name\n";
21
pointer/offset notation
22 for ( int offset1 = 0; offset1 < 4; offset1++ )
23 cout << "*(b + " << offset1 << ") = " << *( b + offset1 ) << '\n';

 2006 Pearson Education,


Inc. All rights reserved.
24
72
25 // output array b using bPtr and array subscript notation
26 cout << "\nPointer subscript notation\n";
Outline
27
28 for ( int j = 0; j < 4; j++ )
29 cout << "bPtr[" << j << "] = " << bPtr[ j ] << '\n';
fig08_20.cpp
30
31 cout << "\nPointer/offset notation\n";
Using pointer subscript
(2 ofnotation
3)
32
33 // output array b using bPtr and pointer/offset notation
34 for ( int offset2 = 0; offset2 < 4; offset2++ )
35 cout << "*(bPtr + " << offset2 << ") = "
36 << *( bPtr + offset2 ) << '\n';
37
38 return 0; // indicates successful termination
39 } // end main Using pointer name and pointer/offset notation

 2006 Pearson Education,


Inc. All rights reserved.
73
Array b printed with:
Outline
Array subscript notation
b[0] = 10
b[1] = 20
b[2] = 30 fig08_20.cpp
b[3] = 40

Pointer/offset notation where the pointer is the array name (3 of 3)


*(b + 0) = 10
*(b + 1) = 20
*(b + 2) = 30
*(b + 3) = 40

Pointer subscript notation


bPtr[0] = 10
bPtr[1] = 20
bPtr[2] = 30
bPtr[3] = 40

Pointer/offset notation
*(bPtr + 0) = 10
*(bPtr + 1) = 20
*(bPtr + 2) = 30
*(bPtr + 3) = 40

 2006 Pearson Education,


Inc. All rights reserved.
1 // Fig. 8.21: fig08_21.cpp 74
2 // Copying a string using array notation and pointer notation. Outline
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 fig08_21.cpp
7 void copy1( char *, const char * ); // prototype
8 void copy2( char *, const char * ); // prototype (1 of 2)
9
10 int main()
11 {
12 char string1[ 10 ];
13 char *string2 = "Hello";
14 char string3[ 10 ];
15 char string4[] = "Good Bye";
16
17 copy1( string1, string2 ); // copy string2 into string1
18 cout << "string1 = " << string1 << endl;
19
20 copy2( string3, string4 ); // copy string4 into string3
21 cout << "string3 = " << string3 << endl;
22 return 0; // indicates successful termination
23 } // end main

 2006 Pearson Education,


Inc. All rights reserved.
24
75
25 // copy s2 to s1 using array notation
26 void copy1( char * s1, const char * s2 )
Use array subscript notationOutline
to copy
27 { string in s2 to character array s1
28 // copying occurs in the for header
29 for ( int i = 0; ( s1[ i ] = s2[ i ] ) != '\0'; i++ )
fig08_21.cpp
30 ; // do nothing in body
31 } // end function copy1
32 (2 of 2)
33 // copy s2 to s1 using pointer notation
34 void copy2( char *s1, const char *s2 ) Use pointer notation to copy string
35 { in s2 to character array in s1
36 // copying occurs in the for header
37 for ( ; ( *s1 = *s2 ) != '\0'; s1++, s2++ )
38 ; // do nothing in body
39 } // end function copy2

string1 = Hello
string3 = Good Bye Increment both pointers to point to
next elements in corresponding arrays

 2006 Pearson Education,


Inc. All rights reserved.
76

8.10 Arrays of Pointers

• Arrays can contain pointers


– Commonly used to store array of strings (string array)
• Array does not store strings, only pointers to strings
• Example
– const char *suit[ 4 ] =
{ "Hearts", "Diamonds", "Clubs", "Spades" };
• Each element of suit points to a char * (string)
• suit array has fixed size (4), but strings can be of any size
• Commonly used with command-line arguments to function
main

 2006 Pearson Education, Inc. All rights reserved.


77

Fig. 8.22 | Graphical representation of the suit array.

 2006 Pearson Education, Inc. All rights reserved.

You might also like