Sunteți pe pagina 1din 38

1

8
Pointers and
Pointer-Based
Strings

2008 Pearson Education, Inc. All rights reserved.

8.1 Introduction
Pointers
Powerful, but difficult to master
Can be used to pass arguments to a function
Can be used to create and manipulate dynamic data
structures
Have close relationship with arrays and strings

2008 Pearson Education, Inc. All rights reserved.

8.2 Pointer Variable Declarations and


Initialization

Pointers are variables that contain memory


addresses as values
Normally, variable contains specific value (direct reference)
Pointers contain address of a variable that has specific value
(indirect reference)

2008 Pearson Education, Inc. All rights reserved.

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)

2008 Pearson Education, Inc. All rights reserved.

Fig. 8.1 | Directly and indirectly referencing a variable.

2008 Pearson Education, Inc. All rights reserved.

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 ys value

2008 Pearson Education, Inc. All rights reserved.

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

2008 Pearson Education, Inc. All rights reserved.

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

2008 Pearson Education, Inc. All rights reserved.

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

2008 Pearson Education, Inc. All rights reserved.

Outline

10

fig08_04.cpp

(1 of 2)
Variable aPtr is
a point to an int

Initialize aPtr with the


address of variable a

2008 Pearson Education,


Inc. All rights reserved.

Address of a and theOutline


value
of aPtr are identical

11

Value of a and the dereferenced


fig08_04.cpp
aPtr are identical
* and & are inverses(2 of 2)
of each other

* and & are inverses; same result


when both are applied to aPtr

2008 Pearson Education,


Inc. All rights reserved.

A pointer may be related to a variable in four ways


1.Non-Constant pointer to Non-Constant data
int main ( )
{
int x = 10, y =20;
int *ptr = &x;
*ptr = 15;
// x=15
ptr = &y;
*ptr = 25;
// y=25
return 0;
}

2. Non-Constant pointer to Constant data


int main ( )
{
int x = 10, y =20;
const int *ptr = &x;
*ptr = 15; // Not permitted
ptr = &y; // Permitted
*ptr = 25; // Not permitted
return 0;
}

A pointer to variable relation continued


3. Constant pointer to Non-Constant data
int main ( )
{
int x = 10, y =20;
int * const ptr = &x;
*ptr = 15; // Permitted, x=15
ptr = &y; // Not permitted
return 0;
}

4. Constant pointer to Constant data


int main ( )
{
int x = 10, y =20;
const int * const ptr = &x;
*ptr = 15; // Not permitted
ptr = &y; // Not Permitted
return 0;
}

8.4 Passing Arguments to Functions by


Reference with Pointers

14

Pointers may be used to pass arguments to a


function, which is known as,
Pass-by-reference with pointer arguments

This is accomplished by,


Passing address of the argument using & operator
Arrays not passed with & because array name is already a
pointer

2008 Pearson Education, Inc. All rights reserved.

A pointer may be passed to a function in four ways


1. Non-Constant pointer to Non-Constant Data
#include <iostream.h>

2. Non-Constant pointer to Constant Data


#include <iostream.h>

void f ( int * );
void f ( const int * );
int main ( )
{
int x = 10;

int main ( )
{
int x = 10;

f ( &x) ;
return 0;

f ( &x) ;
return 0;

}
void f ( int *xPtr)
{
int y = 20;
*xPtr = 100 ; // Permitted
xPtr = &y; // Permitted
}

}
void f ( const int *xPtr )
{
int y = 20;
*xPtr = 100 ; // Not permitted
xPtr = &y; // Permitted
}

A Pointer to a function passing continued


3. Constant pointer to Non-constant Data

4. Constant pointer to Constant Data

#include <iostream.h>
#include <iostream.h>
void f ( int * const);
int main ( )
{ int x = 10;

void f ( const int * const);


int main ( )
{ int x = 10;

f ( &x) ;
return 0;

f ( &x) ;
return 0;

}
}
void f ( int * const xPtr)
{ int y = 20;
*xPtr = 100 ; // Permitted
xPtr = &y; // Not Permitted
}

void f ( const int * const xPtr)


{ int y = 20;
*xPtr = 100 ; // Not permitted
xPtr = &y ;
// Not permitted
}

17

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
Its declaration does not include const qualifier

2008 Pearson Education, Inc. All rights reserved.

18

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

2008 Pearson Education, Inc. All rights reserved.

19

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
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

2008 Pearson Education, Inc. All rights reserved.

20

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

2008 Pearson Education, Inc. All rights reserved.

21

8.8 Arrays and Pointers


int v[5]; //5 element int array on a machine
using 4 byte ints
- vPtr = v; vPtr points to the first
element v[0], at location v[0]
vPtr = &v[ 0 ]; vPtr points to first element v[ 0 ],
at location 3000

2008 Pearson Education, Inc. All rights reserved.

8.8 Pointer Expressions and Pointer


Arithmetic (Cont.)

22

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
vPtr += 2; sets vPtr to 3008 (3000 + 2 * 4)
vPtr points to v[ 2 ]

Returns number of elements between two addresses


vPtr2 = &v[ 2 ];
vPtr = &v[ 0 ];
vPtr2 - vPtr is 2

2008 Pearson Education, Inc. All rights reserved.

23

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

2008 Pearson Education, Inc. All rights reserved.

24

Fig. 8.19 | Pointer vPtr after pointer arithmetic.

2008 Pearson Education, Inc. All rights reserved.

8.8 Pointer Expressions and Pointer


Arithmetic (Cont.)

25

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 *
(void *ptr; int *y, x=5; y = &x;
ptr=y;)
Casting is needed to convert void * to any other
type
void pointers cannot be dereferenced

2008 Pearson Education, Inc. All rights reserved.

8.8 Pointer Expressions and Pointer


Arithmetic (Cont.)

26

Pointer comparison
Use equality and relational operators
Compare addresses stored in pointers
Comparisons are meaningless unless pointers point to
members of the same array

Commonly used to determine whether pointer is 0 (null


pointer)

2008 Pearson Education, Inc. All rights reserved.

8.9 Relationship Between Pointers and


Arrays

27

Arrays and pointers are closely related


Array name is like a constant pointer
void f(int *);
int main( )
{ int v[5];
int a;
f( &a) ;

passing a simple variable to the function f.

f ( v) ;

passing an array to the unction f.

2008 Pearson Education, Inc. All rights reserved.

8.9 Relationship Between Pointers and


Arrays (Cont.)

28

Pointers can do array subscripting operations

Accessing array elements with pointers


Assume declarations:
int b[ 5 ];
int *bPtr;
bPtr = b;
An array element b[ n ] can be accessed by using
pointer/offset notation,
*( bPtr + n ) or *(b+n)
Pointers can be subscripted like an array (pointer/subscript
notation)
bPtr[ 3 ] is same as b[ 3 ]

2008 Pearson Education, Inc. All rights reserved.

8.13.1 Fundamentals of Characters and


Pointer-Based Strings (Cont.)

29

String 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\0" somewhere in memory

Alternative for character array


char color[] = { 'b', 'l', 'u', 'e', '\0' };

2008 Pearson Education, Inc. All rights reserved.

1 // Fig. 8.21: fig08_21.cpp

Outline

2 // Copying a string using array notation and pointer notation.


3 #include <iostream>

30

4 using std::cout;
5 using std::endl;

fig08_21.cpp

6
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

2008 Pearson Education,


Inc. All rights reserved.

Use array subscript notationOutline


to copy
string in s2 to character array s1

31

fig08_21.cpp

(2 of 2)
Use pointer notation to copy string
in s2 to character array in s1

Increment both pointers to point to


next elements in corresponding arrays

2008 Pearson Education,


Inc. All rights reserved.

Function Parameter Passing and Return Types


There are three types of function parameter passing and returning values.
Function parameter type passing can be chosen independent of the type of the
function return.
Parameter Passing
1. Pass-by-value
A copy of the variable is passed to the function. Variable cannot be modified
by the function.
Example:
void modify ( int )
int main ( )
{
int a = 4;
modify ( a );
cout << a << endl; // a = 4;
return 0;
}
void modify (int b)
{
b += 6;
}
Comment : The value of variable a in the main program remained same.
Performance disadvantage: overhead of copying.

2. Pass-by-reference using a reference parameter


A function may modify a variable directly.
Example :
void modify ( int &)
int main ( )
{
int a = 4;
modify ( a );
cout << a << endl; // a= 10
return 0;
}
void modify ( int &b)
{
b +=6;
}
Comment : The value of variable a in the main program has
changed. No performance disadvantage.

3. Pass-by-reference using pointers


A function may modify a variable directly.
Example :
void modify ( int * )
int main ( )
{
int a = 4;
modify ( &a );
cout << a << endl; // a= 10
return 0;
}
void modify ( int *b)
{
*b +=6;
}
Comment : The value of variable a in the main program has changed.
No performance disadvantage.

Observations:
Function calls in the case of pass-by-value and pass-by-reference using
reference parameter are identical. Thus from the function calls it is not
possible to determine which type of these two calls are being used. In the
above function calls in both cases are: modify ( a ). Further inside the
function parameter is being used identically, as b in the above function
modify. We can determine type of parameter passing from the function
prototypes or function header.
Function parameter passing using reference parameter and pointers may
also be distinguished from the function prototype or function header. Thus
& in the prototype indicates reference parameter and * in the prototype
indicates parameter passing by pointers.

Function return types


There are three types of function return types.
1. Return through pass-by-value
A copy of the local variable in the function is returned to the calling program.
Example:
int modify ( int )
int main ( )
{
int a = 4;
// the following call outputs 10.
cout << modify ( a ) << endl;
return 0;
}
int modify (int b)
{
b += 6;
return b;
}

2. Returning a reference
Do not return a reference to a local automatic variable, since such a variable will
be destroyed as soon as the execution of the function is completed.
Example:
In the following example the & sign in the function prototype and the
header indicates that a reference is being returned.
int &modify ( int )

int main ( )
{
int a = 4;
// In the following call c
// becomes a reference to x.
//Then c outputs the value of x.
int &c = modify ( a );
cout << c << endl;
return 0;
}
int &modify (int b)
{ static int x = 3;
b += 2;
x += b ;
return x ;
}
Comment: In the above function returning a reference to variable x works because
static variables exist for the entire duration of the program. On the other hand,

returning a reference to the variable b would not work since it is an automatic local
variable.

3.Returning a pointer
Do not return a pointer to a local automatic variable, since such a variable will be destroyed as soon
as the execution of the function is completed.
Example:
In the following example the * sign in the function prototype and header indicates that a
pointer is being returned.
int *modify ( int )

int main ( )
{ int *c = 0;
int a = 4;
// In the following c is assigned
// the address of x.
//The referencing c outputs
// the value of x.
c = modify ( a );
cout << *c << endl;
return 0;
}
int *modify (int b)
{ static int x = 3;
b += 2;
x += b ;
return &x ;
}

Comment: In the above function returning a pointer to variable x works because static variables exist for
the entire duration of the program. On the other hand, returning a reference to the variable b would not
work since it is an automatic local variable.

S-ar putea să vă placă și