Title: Pointers and Strings
1Chapter 5
21. Introduction
- In this chapter, we discuss one of the most
powerful features of the C programming
language, the pointer. - Pointers are among Cs most difficult
capabilities to master. - This chapter explains basic pointer concepts.
- This chapter also reinforces the intimate
relationship among arrays, pointers, and strings.
32. Pointer Variable Declarations and
Initialization
- Pointer variables contain memory addresses as
their values. - The declaration int intPtr,
count declares the variable intPtr to
be of type int , also count is declared of type
int.
42. Pointer Variable Declarations and
Initialization (cont.)
- Initialization
- Pointers should be initialized either when they
are declared or in an assignment statement. - A pointer may be initialized to NULL or to an
address. - NULL is a symbolic constant defined in the header
file ltiostream.hgt (and several standard library
header files)
53. Pointer Operators
- The , or address operator, is a unary operator
that returns the address of its operand. - Example int y 5 int yPtr
yPtr y assigns the
address of y to the variable yPtr.
63. Pointer Operators (cont.)
- The operator, commonly referred to as the
indirection operator or dereferencing operator,
returns an alias for the object to which its
operand points. - Example cout ltlt yPtr ltlt endl is
equivalent to cout ltlt y ltlt endl
73. Pointer Operators (cont.)
- Errors
- Dereferencing a pointer that has not been
properly initialized. - Attempting to dereference a non-pointer
- Dereferencing a NULL pointer.
- The format in which a pointer is output is
machine dependent. Some systems output pointer
values as hexadecimal integers while others
output them as decimal integers.
84. Calling Functions by Reference
- There are three ways in C to pass arguments to
functions - call-by-value
- call-by-reference with reference arguments
- call-by-reference with pointer arguments.
- This is really passing a pointer by value.
- This section focuses on the last method.
94. Calling Functions by Reference (cont.)
- You must pass an address, and receive a pointer.
(as opposed to passing and receiving any other
datat type, such as an integer). - Prototype void cubeByReference(int )
- Call int number cubeByReference(n
umber)
104. Calling Functions by Reference (cont.)
- Use void cubeByReference (int nPtr)
nPtr nPtr nPtr nPtr
- Note you must dereference the variable in order
to use it as an alias. This was not true with
Reference parameters.
115. Using the const qualifier with Pointers
- Introduction
- The const qualifier enables the programmer to
inform the compiler that the value of a
particular variable should not be modified. - The const qualifier can be used to enforce the
principle of least privilege. - If a value does not (or should not) change in the
body of a function to which it is passed, the
parameter should be declared const to ensure that
it is not accidentally modified.
125. Using the const qualifier with Pointers (cont.)
- There are four ways to pass a pointer to a
function - a non-constant pointer to non-constant data
- void func ( char )
- a non-constant pointer to constant data
- void func ( const char )
135. Using the const qualifier with Pointers (cont.)
- a constant pointer to non-constant data
- an array name is a constant pointer to the
beginning of an array (a a0) - int x int const ptr x ptr
7 //x can be modified, but ptr will
always point to x
145. Using the const qualifier with Pointers (cont.)
- a constant pointer to constant data int x
3 const int const ptr x int y
//the following are
illegal ptr y ptr 5
156. Bubble sort using Call-by-reference
- First, write a swap function void swap
( int elem1, int elem2) int hold
elem1 elem1 elem2 elem2
hold
16- Then write a Bubble Sort Function void
bubbleSort(int array, const int size)
void swap (int , int )
int i, pass for(pass0 pass lt size
-1 pass) for(i0 iltsize-1 i)
if(arrayigtarrayi1)
swap(arrayi, arrayi1)
176. Bubble sort using Call-by-reference (cont.)
- Things to note
- The first parameter (int array) could have been
int array - The parameter size is declared a const
- The prototype for swap is included in the body of
bubbleSort. This enforces the principle of least
privilege by restricting calls to swap.
186. Bubble sort using Call-by-reference (cont.)
- Things to note (cont.)
- When passing an array to a function, also pass
the size of the array (rather than building into
the function knowledge of the array size). This
helps make the function more general. General
functions are often reusable in many programs.
196. Bubble sort using Call-by-reference (cont.)
- sizeof operator
- C provides the unary operator sizeof to
determine the size of any data type in bytes
during the program. - When applied to an array it returns the number of
bytes - When applied to a pointer parameter in a function
it returns the size of the pointer, not the size
of the array it may point to.
206. Bubble sort using Call-by-reference (cont.)
- sizeof operator (cont.)
- The number of elements in an array can also be
determined using the results of two sizeof
calls. double realArray22
numElements sizeof (realArray) /
sizeof(double)
217. Pointer Expressions and Pointer Arithmetic
- Pointers are valid operands in arithmetic
expressions, assignment expressions, and
comparison expressions. - This section describes the operators that can
have pointers as operands and how these operators
are used.
227. Pointer Expressions and Pointer Arithmetic
(cont.)
- Arithmetic operations performed on pointers
- pointers may be incremented () or decremented
(--) - Note this does not just add or subtract 1 from
the pointer, but adds or subtracts 1sizeof (what
the pointer points to) - an integer may be added to ( or ) or
subtracted from (- or -) a pointer. - one pointer may be subtracted from another.
237. Pointer Expressions and Pointer Arithmetic
(cont.)
- Pointer arithmetic problems
- Using pointer arithmetic on a pointer that does
not refer to an array of values is normally a
logic error. - Running off either end of an array when using
pointer arithmetic is normally a logic error. - Because the results of pointer arithmetic depend
on the size of the objects a pointer points to,
pointer arithmetic is machine dependent. - Therefore it is not recommended that you use
pointer arithmetic in this class.
247. Pointer Expressions and Pointer Arithmetic
(cont.)
- void
- a generic pointer capable of representing any
pointer type. - dereferencing a void pointer is a syntax error.
- a void cannot be assigned directly to another
pointer without proper type casting.
257. Pointer Expressions and Pointer Arithmetic
(cont.)
- Pointer comparison
- Pointers can be compared using equality and
relational operators. - such comparisons are usually 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 NULL
268. The Relationship between Pointers and Arrays
- Arrays and pointers are intimately related in C
and may be used almost interchangeably. - an array name is a constant pointer.
- pointers can be used to do any operation
involving array subscripting.
278. The Relationship between Pointers and Arrays
(cont.)
- Example
- int b5, bptr bptr b
- bptr b and bptr b0 are
equivalent. - bptr3, b3, and (bptr3) are equivalent
289. Arrays of Pointers
- Arrays may contain pointers.
- A common use of such a data structure is to form
an array of strings, referred to simply as a
string array. - char suit4 Hearts, Diamonds, Clubs,
Spades
2910. Card Shuffling and Dealing Simulation
- This section presents the development of a
program that uses a random number generator to
develop a card shuffling and dealing simulation
program. - srand(time(0))
- num rand()
3011. Function Pointers
- A pointer to a function contains the address of
the function in memory. - Just as with an array, the name of the function
is the pointer to the function. - Pointers to functions can be passed to functions,
returned, stored,...
3111. Function Pointers (cont.)
- Example
- Prototype
- void bubble(int , const int, int()(int,
int)) int ascending(int, int) int
descending(int, int) - Call
- bubble(a, arraySize, ascending)
3211. Function Pointers (cont.)
- Header
- void bubble (int work , const int size, int
(compare)(int, int)) - Call of compare from inside bubble
- if( (compare)(workcount,workcount1) )
- The following call also works
- if( compare(workcount,workcount1) )
- but you do not see that compare is a function
pointer in this call.
3311. Function Pointers (cont.)
- One use of function pointers is in menu-driven
systems. void func1(int) void
func2(int) void func3(int)
void (f3)(int)func1, func2,
func3 (fchoice)(choice)
3412. Introduction to Character and String
Processing
- In this section we introduce some common standard
library functions that facilitate string
processing. - We use pointer-based strings here.
- Later in the book we include a full chapter on
strings a full-fledged objects (Chap 19).
3512.1 Fundamentals of Characters and Strings
- Constants
- Character constants are in single quotes a
- String constants are in double quotes a
- Note string constants have a NULL terminator
- Example 1
- char word20 cin gtgt setw(20)gtgt word
- The setw ensures that the string read into word
does not exceed the size of the array.
3612.1 Fundamentals of Characters and Strings
(cont.)
- Example 2
- char sentence80 cin.getline(sentence, 80,
\n) - The function stops reading characters when
- the delimiter, \n, is encountered,
- the end-of-file indicator is entered,
- or when the number of characters read so far is
one less than the length specified, 80.
3712.2 String Manipulation Functions of the String
Handling Library
- The string handling library provides many useful
functions for - manipulating string data,
- comparing strings,
- searching strings for characters and other
strings, - tokenizing strings, and
- determining the length of strings.
3812.2 String Manipulation Functions of the String
Handling Library (cont.)
- char strcpy(char s1, const char s2)
- copies the string s2 into the array s1
- char strcat (char s1, const char s2)
- Appends string s2 to string s1
- int strcmp(const char s1, const char s2)
- compares string s1 to s2. Returns lt0, 0, gt0
- size_t strlen(const char s)
- determines the length of string s.