Pointers and Strings

advertisement
Pointers and Strings
Chapter 5
1
2
What You Will Learn . . .

Passing arguments to
functions with pointers
Pointers can point
to functions
How to use pointers
See relationship of
pointers to strings and
arrays
Declaring & using
arrays of strings
3
Introduction


Pointer variables contain memory
addresses as their values
Contrast normal variables which contain
a specific value
x
5
int *xptr, x;
xptr


x holds a value
xptr holds memory address of some int
location
4
Pointer Variable Declarations and
Initializations

Must declare the type of variable to
which pointer variable will point
float


amt, *fptr;
Must use the leading * to specify this is
a pointer variable
Good idea to include ptr in the name
of the pointer variable
5
Pointer Initialization


When declared, variables should NOT
be assumed to have any certain value
As with all variables, pointer variables
should be explicitly initialized
– Initialized with address of a specific
variable
– Initialized to 0 or NULL (points to nothing)
6
Pointer Operators

Address operator
&
– unary operator
– returns address of operand
int *xptr, x;
x
x = 5;
xptr = &x;
xptr
5
7
Pointer Operators

Address operator
&
– unary operator
– returns address of operand
int *xptr, x;
x = 5;
xptr = &x;
Values actually stored
Address
1234
6500
x
5
xptr 1234
8
Pointer Operators

The indirection or dereferencing
operator
– Use the * symbol

*xptr will yield the value stored at
the location to which xptr points
int x, *xptr;
x = 50;
xptr = &x;
cout << *xptr;
// what gets printed?
50
9
Pointer Operators

The precedence of
– & the address operator
– * the dereferencing operator


Higher precedence than multiplication
and division
Lower precedence than parentheses
10
Calling Functions by Reference

Three ways to pass arguments to a
function
– call by value
– call by reference with reference
parameters
– call by reference with pointer parameters
void doit (int amt);
void whatever ( float &value);
void fribble (char *ch);
11
Calling Functions by Reference

Call by value
– value gets passed one way (to the
function) only
– can use constant, expression, or variable
in call

Reference parameter
– value passed both ways
– must use variable in call
– parameter automatically dereferenced
locally
12
Calling Functions by Reference

Must use address in call
– use address operator
fribble (&c1);

Must explicitly dereference locally within
function
– use * operator
void fribble (char *ch)
{ *ch = …. ; }
13
Using the const Qualifier with
Pointers


Recal that const informs the compiler
that the value of a "variable" should not
be modified
This can also be used on function
parameters so that actual parameters
are NOT affected by changes in formal
parameters
void try_a_change (const char *s_ptr)
14
const Used on Parameters

When used, do not try to alter contents
of where pointer points to
void double_int (const int *num_ptr)
{
*num_ptr = 2 * *num_ptr;
}
compiler error 
15
const Used on Parameters

Consider the advantage of passing
large data objects (structures, arrays)
using points to constant data
– saves memory
• function does not need to create duplicate data
object
– saves time
• program need not copy large number of bytes
to the local object
16
Bubble Sort Using Call-byreference


Refer to “Cyber Classroom” CD for
author’s description of the program
Run the program
17
Bubble Sort Using Call-byreference -- Note ...


array declared as int *array
not
int array [ ]
Parameter size declared as const to
enforce sorting function not altering size
– when passing an array to function, send
size also -- don’t have it built in

Prototype for swap included inside
bubbleSort -- it is the only function that
calls swap
18
Pointer Expressions & Pointer
Arithmetic

Pointer values are valid operands in
expressions
– arithmetic
– assignment
– comparison

Not all such operators are valid with
pointer variables
19
Pointer Expressions & Pointer
Arithmetic

Valid operations on pointers
++ - + += - - =
int v[5], *vPtr;
vPtr = v; // same as vPtr = &v[0];
20
Pointer Expressions & Pointer
Arithmetic

Consider:
vPtr += 2;
// same as vPtr = vPtr + 2;
/* But, beware of
vPtr -= 4;
Why?
21
Pointer Expressions & Pointer
Arithmetic -- warnings !!




Beware use of pointer arithmetic on pointers
which do not reference an array
Consider results of subtracting or comparing
two pointers which do not reference the same
array
C++ has no range checking -- if you run off
the end of an array, you can be in trouble
Pointers can be assigned to other pointers
only if they are pointers to the same type
– although typecasting can be used (carefully)
22
Pointers to void ( void * )

This is a generic pointer
– can represent any pointer type



All pointer types can be assigned a
pointer to void without casting
A pointer to void cannot be be assigned
a pointer of another type (without
casting)
Void pointer cannot be dereferenced
(why not??)
23
Relationship Between Pointers
and Arrays



// Given
int list [5], *intPtr;
intPtr = list; // name of array is a pointer constant, an address
Then we can use either
list[2] or
*(intPtr + 2)
to reference the second element of the
array
The former is clearer but takes longer to
compile
24
Relationship Between Pointers
and Arrays

Note how pointer is used to traverse
array:
int b[] = { 10, 20, 30, 40 };
int *bPtr = b;
// set bPtr to point to array b
for ( offset = 0; offset < 4; offset++ )
cout << "*(bPtr + " << offset << ") = "
<< *( bPtr + offset ) << '\n';
for (bPtr = b; bPtr < b + 4; bPtr++)
cout << *bPtr << '\n';
How are these
two different?
25
Relationship Between Pointers
and Arrays

What is wrong with this use of the name
of the array?
for ( bPtr = b ; b < bPtr + 4; b++ )
cout << *b << '\n';
The name of the array is a
pointer constant
26
Arrays of Pointers

Common use is for an array of strings
(character arrays)
char *suit [4] = {"Hearts","Diamonds",
"Clubs", "Spades"};
27
Arrays of Pointers
char *suit [4] = {"Hearts",
"Diamonds", "Clubs", "Spades"};


Character values stored in memory, one
byte longer than length of string
Array suit actually holds pointers to
these locations
– point to first character of each string

Note that memory not wasted for
unneeded
characters of
shorter strings
28
Function Pointers



Pointer to a function contains the
address of the function in memory
A function name is a pointer constant to
the starting address in memory of the
code of the function
Pointers to functions can be …
– passed as parameters (both directions)
– stored in arrays
– assigned to other function pointers
29
Function Pointers

Consider the following code:
void bubble( int [], const int, int (*)( int, int ) );
int ascending( int, int );
int descending( int, int );
. . .
void bubble( int work[], const int size,
int (*compare)( int, int ) )

Function sort receives a pointer to a
function
– function ascending
– function descending
depending on
pointer passed in call
30
Function Pointers

Sending a function name as the actual
parameter sends the address of that
function to another function
if ( order == 1 ) {
bubble( a, arraySize,
cout << "\nData items
}
else {
bubble( a, arraySize,
cout << "\nData items
}
ascending );
in ascending order\n";
descending );
in descending order\n";
31
Function Pointers

Consider an array of functions

void (*f [3] ) ( int ) = { f1, f2, f3 };
Assumptions
– f1, f2, and f3 have been previously
declared
– each has a single int parameter
– they are called with an array number
f [ choice ] (x_int);
32
Characters and Strings

Character constant
– an integer value represented as a
character in single quotes 'x' or '\t'

String
– series of characters treated as a single unit

String constants (string literals)
– enclosed in double quotes
"Hi Mom"
"2/14/1999"
33
Strings

An array of characters ending in the null
character '\0'

Accessed via pointer to first character in
the string
Value of a string

– the constant address of its first character

Assigned in declaration as array or char
pointer
char name[ ] = "Snuffy Snail";
char *addr = "123 Frogpond";
34
Strings

Make sure to allocate enough
characters in the array to have room for
the '\0'

If you create a "string", make sure the
'\0' gets tagged on the end

Passing a character as a parameter
when a string is expected can cause run
time problems
Vice-versa is a syntax error

35
String Manipulation Functions

Recall that strings must be handled in a
special manner
Don't do it!! Why?
char name[30];
name = "Osgood Smart";

Use functions provided
– See page 325
– make sure to
#include <string.h>
Download