Sunteți pe pagina 1din 11

Contents

Introduction
Pointers (Declaration and Initialization, Operators)
Calling Function by Reference
Object Oriented Programming Using Const Keyword
Pointer Examples , Pass by Reference (Bubble Sort)
Pointer Expression and Arithmetic
Relationship Between Pointers and Arrays
Arrays of Pointers
Introduction to Character and Strings
String Manipulation Functions

Pointers Pointers: Declaration & Initialization


Declarations and Initialization
Pointer variables
Pointers are :
Contain memory addresses as values

Powerful, but difficult to master Normally, variable contains specific value (direct reference)

Simulate pass-by-reference Pointers contain address of variable that has specific value (indirect reference)

Close relationship with arrays and strings Indirection


countPtr count
Referencing value through pointer

Pointer declarations 7
* indicates variable is pointer
int *myPtr;
count
declares pointer to int, pointer of type int *
Multiple pointers require multiple asterisks 7
int *myPtr1, *myPtr2;

Pointers: Declaration & Initialization Pointers: Operators


& (address operator)
Can declare pointers to any data type
Returns memory address of its operand
Pointer initialization Example
Initialized to 0, NULL, or address int y = 5;
int *yPtr;
0 or NULL points to nothing yPtr = &y; // yPtr gets address of y
yPtr points to y

y yptr y

yPtr 5 500000 600000 600000 5

address of
y is value
of yptr
Pointers: Operators Pointers: Operators
2 // Using the & and * operators.
3 #include <iostream>
4
* (indirection/dereferencing operator) 5 using std::cout;
6 using std::endl;
Returns synonym for object its pointer operand points to 7
8 int main()
9 {
*yPtr returns y (because yPtr points to y). 10 int a; // a is an integer
11 int *aPtr; // aPtr is a pointer to an integer
dereferenced pointer is l value 12
13 a = 7;
14 aPtr = &a; // aPtr assigned address of a
15
16 cout << "The address of a is " << &a
* and & are inverses
*yptr = 9; // assigns 9 to y 17 << "\nThe value of aPtr is " << aPtr;
18 of each other
19 cout << "\n\nThe value of a is " << a
20 << "\nThe value of *aPtr is " << *aPtr;
21
* and & are inverses of each other 22 cout << "\n\nShowing that * and & are inverses of "

23 << "each other.\n&*aPtr = " << &*aPtr

24 << "\n*&aPtr = " << *&aPtr << endl;


25
26 return 0; // indicates successful termination
27 } // end main

Pointers: Operators Calling Functions By Reference


The address of a is 0012FED4
3 ways to pass arguments to function
The value of aPtr is 0012FED4
Pass-by-value
Pass-by-reference with reference arguments
The value of a is 7 Pass-by-reference with pointer arguments
The value of *aPtr is 7
return can return one value from function
Showing that * and & are inverses of each other.
Arguments passed to function using reference
&*aPtr = 0012FED4 arguments
*&aPtr = 0012FED4 * and & are inverses; Modify original values of arguments
same result when both More than one value returned
applied to aPtr

Calling Functions By Reference Calling Functions By Reference


1 //
2 // Cube a variable using pass-by-value.
3 #include <iostream>
4

Pass-by-reference with pointer arguments 5


6
using std::cout;
using std::endl;
7
8 int cubeByValue( int ); // prototype
Simulate pass-by-reference 9
10 int main()

Use pointers and indirection operator 11 { Pass number by value; result


12 int number = 5;
13 returned by cubeByValue
14 cout << "The original value of number is " << number;
Pass address of argument using & operator 15
16 // pass number by value to cubeByValue
17 number = cubeByValue( number );
Arrays not passed with & because array name already 18
19 cout << "\nThe new value of number is " << number << endl;
20
pointer 21 return 0; // indicates successful termination
22
23 } // end main
* operator used as alias/nickname for variable inside of 24
25 // calculate and return cube of integer argument
26 int cubeByValue( int n )
function 27 {
28 return n * n * n; // cube local variable n and return result
29
30 } // end function cubeByValue

The original value of number is 5


The new value of number is 125
Calling Functions By Reference Using Const With Pointers
2 // Cube a variable using pass-by-reference
3 // with a pointer argument.
const qualifier
4 #include <iostream>
5 Value of variable should not be modified
6 using std::cout;
7 using std::endl;
8 const used when function does not need to change a variable
9 void cubeByReference( int * ); // prototype
10
11 int main()12 { Principle of least privilege
13 int number = 5;
14
Award function enough access to accomplish task, but no more
15 cout << "The original value of number is " << number;
16
17 // pass address of number to cubeByReference
Four ways to pass pointer to function
18 cubeByReference( &number ); Nonconstant pointer to nonconstant data
19
20 cout << "\nThe new value of number is " << number << endl;
-Highest amount of access
21 Nonconstant pointer to constant data
22 return 0; // indicates successful termination
24 } // end main
Constant pointer to nonconstant data
25 Constant pointer to constant data
26 // calculate cube of *nPtr; modifies variable number in main
27 void cubeByReference( int *nPtr ) {
- Least amount of access
29 *nPtr = *nPtr * *nPtr * *nPtr; // cube *nPtr
The original value of number is 5
30
31 } // end function cubeByReference The new value of number is 125

Using Const With Pointers Using Const With Pointers


2 // Converting lowercase letters to uppercase letters
26 // convert string to uppercase letters
3 // using a non-constant pointer to non-constant data.
27 void convertToUppercase( char *sPtr )
4 #include <iostream>
28 {
5
29 while ( *sPtr != '\0' ) { // current character is not '\0'
6 using std::cout;
30
7 using std::endl;
31 if ( islower( *sPtr ) ) // if character is lowercase,
8
32 *sPtr = toupper( *sPtr ); // convert to uppercase
9 #include <cctype> // prototypes for islower and toupper
33
10
34 ++sPtr; // move sPtr to next character in string
11 void convertToUppercase( char * );
35
12
36 } // end while
13 int main() 14 {
37
15 char phrase[] = "characters and $32.98";
38 } // end function convertToUppercase
16
17 cout << "The phrase before conversion is: " << phrase;
18 convertToUppercase( phrase );
The phrase before conversion is: characters and $32.98
19 cout << "\nThe phrase after conversion is: " << phrase << endl;
21 The phrase after conversion is: CHARACTERS AND $32.98
22 return 0; // indicates successful termination
24 } // end main

Using Const With Pointers Using Const With Pointers


2 // Printing a string one character at a time using
23 // sPtr cannot modify the character to which it points,
3 // a non-constant pointer to constant data.
24 // i.e., sPtr is a "read-only" pointer
4 #include <iostream>
25 void printCharacters( const char *sPtr )
5
26 {
6 using std::cout; Parameter is constant pointer to
constant data 27 for ( ; *sPtr != '\0'; sPtr++ ) // no initialization
7 using std::endl; sPtr is nonconstant pointer to
28 cout << *sPtr; constant data; cannot modify
8
29 character to which sPtr points.
9 void printCharacters( const char * );
30 } // end function printCharacters
10
11 int main() {
13 char phrase[] = "print characters of a string";
14 Increment sPtr to point to next
character.
15 cout << "The string is:\n";
16 printCharacters( phrase );
17 cout << endl; Pass pointer phrase to function
printCharacters.
18
19 return 0; // indicates successful termination
21 } // end main
Using Const With Pointers Using Const With Pointers
2 // Attempting to modify data through a
3 // non-constant pointer to constant data.
4
5 void f( const int * ); // prototype
const pointers
6 Always point to same memory location
7 int main() 8 {
9 int y;
Default for array name
11 f( &y ); // f attempts illegal modification Must be initialized when declared
12
13 return 0; // indicates successful termination
15 } // end main
16
17 // xPtr cannot modify the value of the variable
18 // to which it points
19 void f( const int *xPtr ) {
21 *xPtr = 100; // error: cannot modify a const
22 object
23 } // end function f

2 // Attempting to modify a constant pointer to constant data.


1 // 3 #include <iostream>
5 using std::cout; ptr is constant pointer to integer.
2 // Attempting to modify a constant pointer to
6 using std::endl;
3 // non-constant data. 7
4 8 int main() 9 {
10 int x = 5, y;
5 int main() { ptr is constant pointer to integer. 11
7 int x, y; 12 // ptr is a constant pointer to a constant integer.
8 13 // ptr always points to the same location; the Cannot
integermodify x (pointed to by ptr) since
14 // at that location cannot be modified.
9 // ptr is a constant pointer to an integer that can *ptr declared constant.
15 const int *const ptr = &x;
10 // be modified through ptr, but ptr always points to the 16
11 // same memory location. 17 cout << *ptr << endl;
Can modify x (pointed to by ptr) 18
12 int * const ptr = &x;
since x not constant. 19 *ptr = 7; // error: *ptr is const; cannot assign new value
13 20 ptr = &y; // error: ptr is const; cannot assign new address
14 *ptr = 7; // allowed: *ptr is not const 21
22 return 0; // indicates successful termination
15 ptr = &y; // error: ptr is const; cannot assign new 24 } // end main Cannot modify ptr to point to
address new address since ptr is
16 constant.
17 return 0; // indicates successful termination
Cannot modify ptr to point Line 19 generates compiler error Line 20 generates compiler error
18 by attempting to assign new
to new address since ptr is by attempting to modify constant
19 } // end main address to constant pointer.
constant. object.
Line 15 generates compiler error
by attempting to assign new d:\cpp\oop\code.cpp (19) : error C2166:
address to constant pointer. l-value specifies const object
d:\cpp\oop\code.cpp(15) : error C2166: d:\cpp\oop\code.cpp (20) : error C2166:
l-value specifies const object l-value specifies const object

Bubble Sort Using Pass-by-Reference 1 //


2 // This program puts values into an array, sorts the values into
3 // ascending order, and prints the resulting array.
4 #include <iostream>
Implement bubbleSort using pointers 5
6 using std::cout;
Want function swap to access array elements 7
8
using std::endl;

Individual array elements: scalars 9


10
#include <iomanip>

Passed by value by default 11 using std::setw;


12
Pass by reference using address operator & 13 void bubbleSort( int *, const int ); // prototype
14 void swap( int * const, int * const ); // prototype
15
16 int main()
17 {
18 const int arraySize = 10;
19 int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
20
21 cout << "Data items in original order\n";
22
23 for ( int i = 0; i < arraySize; i++ )
24 cout << setw( 4 ) << a[ i ];
25
26 bubbleSort( a, arraySize ); // sort the array 51
27 52 } // end function bubbleSort
28 cout << "\nData items in ascending order\n"; 53
29 Declare as int *array (rather than 54 // swap values at memory locations to which
30 for ( int j = 0; j < arraySize; j++ ) int array[]) to indicate function
55 // element1Ptr and element2Ptr point
31 cout << setw( 4 ) << a[ j ]; bubbleSort receives single-
32 subscripted array.
56 void swap( int * const element1Ptr, int * const
33 cout << endl; element2Ptr )
34 57 {
35 return 0; // indicates successful termination 58 int hold = *element1Ptr;
36 59 *element1Ptr = *element2Ptr;
37 } // end main 60 *element2Ptr = hold;
38 Pass arguments by reference,
39 // sort an array of integers using bubble sort algorithm
61
62 } // end function swap allowing function to swap values
40 void bubbleSort( int *array, const int size ) at memory locations.
41 {
42 // loop to control passes
43 for ( int pass = 0; pass < size - 1; pass++ ) Receives size of array
44 as argument; declared
45 // loop to control comparisons during each pass const to ensure size
46 for ( int k = 0; k < size - 1; k++ ) not modified.
47
48 // swap adjacent elements if they are out of order
49 if ( array[ k ] > array[ k + 1 ] ) Data items in original order
2 6 4 8 10 12 89 68 45 37
50 swap( &array[ k ], &array[ k + 1 ] ); Data items in ascending order
2 4 6 8 10 12 37 45 68 89

Bubble Sort Using Pass-by-Reference 2


3
// Sizeof operator when used on an array name
// returns the number of bytes in the array.
4 #include <iostream>
5
6 using std::cout;
sizeof 7
8
using std::endl;

9 size_t getSize( double * ); // prototypeOperator sizeof applied to an


Unary operator returns size of operand in bytes 10 array returns total number of
11 int main() { bytes in array.
For arrays, sizeof returns 13 double array[ 20 ];
( size of 1 element ) * ( number of elements ) 14
15 cout << "The number of bytes in the array is "
If sizeof( int ) = 4, then 16 << sizeof( array );
int myArray[10]; 17
18 cout << "\nThe number of bytes returned by getSize is "
cout << sizeof(myArray); 19 << getSize( array ) << endl;
20
will print 40 21 return 0; // indicates successful termination
23 } // end main
24 Function getSize returns number of
25 // return size of ptr
sizeof can be used with 26
28
size_t getSize( double *ptr ) {
return sizeof( ptr );
bytes used to store array address.

Variable names 29 Operator sizeof returns number


30 } // end function getSize of bytes of pointer.
Type names
Constant values
The number of bytes in the array is 160
The number of bytes returned by getSize is 4

1 // 20 cout << "sizeof c = " << sizeof c


21 << "\tsizeof(char) = " << sizeof( char )
2 // Demonstrating the sizeof operator. Operator sizeof can be used
22 << "\nsizeof s = " << sizeof s
3 #include <iostream> on variable name.
23 << "\tsizeof(short) = " << sizeof( short )
4 24 << "\nsizeof i = " << sizeof i
5 using std::cout; 25 << "\tsizeof(int) = " << sizeof( int )
26 << "\nsizeof l = " << sizeof l
6 using std::endl; 27 << "\tsizeof(long) = " << sizeof( long ) Operator sizeof can be
7 28 << "\nsizeof f = " << sizeof f used on type name.
8 int main() 29 << "\tsizeof(float) = " << sizeof( float )
30 << "\nsizeof d = " << sizeof d
9 { 31 << "\tsizeof(double) = " << sizeof( double )
10 char c; 32 << "\nsizeof ld = " << sizeof ld
11 short s; 33 << "\tsizeof(long double) = " << sizeof( long double )
12 int i; 34 << "\nsizeof array = " << sizeof array
35 << "\nsizeof ptr = " << sizeof ptr
13 long l; 36 << endl;
14 float f; 37
15 double d; 38 return 0; // indicates successful termination
39
16 long double ld; 40 } // end main
17 int array[ 20 ];
18 int *ptr = array;
19
sizeof c = 1 sizeof(char) = 1 Pointer Expressions and Pointer Arithmetic
sizeof s = 2 sizeof(short) = 2
sizeof i = 4 sizeof(int) = 4
sizeof l = 4 sizeof(long) = 4 Pointer arithmetic
sizeof f = 4 sizeof(float) = 4 Increment/decrement pointer (++ or --)
sizeof d = 8 sizeof(double) = 8 Add/subtract an integer to/from a pointer( + or += , - or -=)
sizeof ld = 8 sizeof(long double) = 8 Pointers may be subtracted from each other
sizeof array = 80 Pointer arithmetic meaningless unless performed on pointer to
sizeof ptr = 4 array

5 element int array on a machine using 4 byte ints


vPtr points to first element v[ 0 ], which is at location 3000
vPtr = 3000
location
vPtr += 2; sets vPtr to 3008 3000 3004 3008 3012 3016

vPtr points to v[ 2 ]
v[0] v[1] v[2] v[3] v[4]

pointer variable vPtr

Pointer Expressions and Pointer Arithmetic Pointer Expressions and Pointer Arithmetic

Subtracting pointers Pointer comparison


Returns number of elements between two addresses
vPtr2 = v[ 2 ]; Use equality and relational operators
vPtr = v[ 0 ]; Comparisons meaningless unless pointers point
vPtr2 - vPtr == 2 to members of same array
Pointer assignment Compare addresses stored in pointers
Pointer can be assigned to another pointer if both of Example: could show that one pointer points to
same type
If not same type, cast operator must be used higher numbered element of array than other
Exception: pointer to void (type void *) pointer
Generic pointer, represents any type
No casting needed to convert pointer to void pointer Common use to determine whether pointer is 0
void pointers cannot be dereferenced
(does not point to anything)

Relationship Between Pointers and Arrays 1 //


2 // Using subscripting and pointer notations with arrays.
3
4 #include <iostream>
5
Arrays and pointers closely related 6 using std::cout;
7 using std::endl;
Array name like constant pointer 8
Pointers can do array subscripting operations 9 int main()
10 {
11 int b[] = { 10, 20, 30, 40 };
Accessing array elements with pointers 12 int *bPtr = b; // set bPtr to point to array b
13
Element b[ n ] can be accessed by *( bPtr + n ) 14 // output array b using array subscript notation
Called pointer/offset notation 15 cout << "Array b printed with:\n"
16 << "Array subscript notation\n";
Addresses 17
&b[ 3 ] same as bPtr + 3 18 for ( int i = 0; i < 4; i++ )
Array name can be treated as pointer 19 cout << "b[" << i << "] = " << b[ i ] << '\n';
20
b[ 3 ] same as *( b + 3 ) 21 // output array b using the array name and
Pointers can be subscripted (pointer/subscript notation) 22 // pointer/offset notation
bPtr[ 3 ] same as b[ 3 ] 23 cout << "\nPointer/offset notation where "
24 << "the pointer is the array name\n";
25
26 for ( int offset1 = 0; offset1 < 4; offset1++ ) Array b printed with:
27 cout << "*(b + " << offset1 << ") = "
28 << *( b + offset1 ) << '\n'; Using array name and Array subscript notation
29 b[0] = 10
pointer/offset notation.
30 // output array b using bPtr and array subscript notation b[1] = 20
31 cout << "\nPointer subscript notation\n"; b[2] = 30
32 b[3] = 40
33 for ( int j = 0; j < 4; j++ )
Pointer/offset notation where the pointer is the array name
34 cout << "bPtr[" << j << "] = " << bPtr[ j ] << '\n';
*(b + 0) = 10
35
Using pointer subscript notation. *(b + 1) = 20
36 cout << "\nPointer/offset notation\n";
*(b + 2) = 30
37 *(b + 3) = 40
38 // output array b using bPtr and pointer/offset notation
39 for ( int offset2 = 0; offset2 < 4; offset2++ ) Pointer subscript notation
40 cout << "*(bPtr + " << offset2 << ") = " bPtr[0] = 10
41 << *( bPtr + offset2 ) << '\n'; bPtr[1] = 20
42 bPtr[2] = 30
43 return 0; // indicates successful termination bPtr[3] = 40
44
45 } // end main Using bPtr and pointer/offset Pointer/offset notation
notation. *(bPtr + 0) = 10
*(bPtr + 1) = 20
*(bPtr + 2) = 30
*(bPtr + 3) = 40

1 // 26
2 // Copying a string using array notation Use array subscript notation to
3 // and pointer notation.
27 } // end main
copy string in s2 to character
4 #include <iostream> 28 array s1.
5 29 // copy s2 to s1 using array notation
6 using std::cout; 30 void copy1( char *s1, const char *s2 )
7 using std::endl;
8 31 {
9 void copy1( char *, const char * ); // prototype 32 for ( int i = 0; ( s1[ i ] = s2[ iUse]pointer) != '\0';
notation to copy
10 void copy2( char *, const char * ); // prototype i++ ) string in s2 to character array in
11 s1.
12 int main()
33 ; // do nothing in body
13 { 34
14 char string1[ 10 ]; 35 } // end function copy1
15 char *string2 = "Hello";
16 char string3[ 10 ];
36
17 char string4[] = "Good Bye"; 37 // copy s2 to s1 using pointer notation
Increment both pointers to point
18 38 void copy2( char *s1, const char to next )
*s2 elements in
19 copy1( string1, string2 ); corresponding arrays.
39 {
20 cout << "string1 = " << string1 << endl;
21
40 for ( ; ( *s1 = *s2 ) != '\0'; s1++, s2++ )
22 copy2( string3, string4 ); 41 ; // do nothing in body
23 cout << "string3 = " << string3 << endl; 42
24 string1 = Hello
43 } // end function copy2
25 return 0; // indicates successful termination
string3 = Good Bye

Case Study: Card Shuffling and Dealing Simulation


Arrays of Pointers
Arrays can contain pointers Card shuffling program
Commonly used to store array of strings Use an array of pointers to strings, to store suit names
char *suit[ 4 ] = {"Hearts", "Diamonds", Use a double scripted array (suit by value)
"Clubs", "Spades" };
Each element of suit points to char * (a string) Ace Two Three Four Five Six Seven Eight Nine Ten Jack Queen King
Array does not store strings, only pointers to strings 0 1 2 3 4 5 6 7 8 9 10 11 12

Hearts 0
suit[0] H e a r t s \0
Diamonds 1
suit[1] D i a m o n d s \0 Clubs 2
Spades 3
suit[2] C l u b s \0
deck[2][12] represents the King of Clubs
suit[3] S p a d e s \0

Clubs King

Place 1-52 into the array to specify the order in which the cards
suit array has fixed size, but strings can be of any size are dealt
Case Study: Card Shuffling and Dealing Nine of Spades Seven of Clubs
Five of Spades Eight of Clubs
Simulation Queen of Diamonds Three of Hearts
Jack of Spades Five of Diamonds
Jack of Diamonds Three of Diamonds
Three of Clubs Six of Clubs
Pseudocode for shuffling and dealing simulation Ten of Clubs Nine of Diamonds
Ace of Hearts Queen of Hearts
Seven of Spades Deuce of Spades
Third refinement Six of Hearts Deuce of Clubs
First refinement Ace of Clubs Deuce of Diamonds
Second refinement Nine of Hearts Seven of Diamonds
Choose slot of deck randomly
Initialize the suit array Six of Spades Eight of Diamonds
For each of the 52 cards Ten of Spades King of Hearts
Initialize the face array While chosen slot of deck has
Initialize the deck array
Four of Clubs Ace of Spades
Place card number in randomly been previously chosen Ten of Hearts Four of Spades
selected unoccupied slot of deck Choose slot of deck randomly Eight of Hearts Eight of Spades
Place card number in chosen Jack of Hearts Ten of Diamonds
Shuffle the deck slot of deck Four of Diamonds King of Diamonds
Seven of Hearts King of Spades
Queen of Spades Four of Hearts
For each of the 52 cards For each slot of the deck array Nine of Clubs Six of Diamonds
Deal 52 cards Deuce of Hearts Jack of Clubs
King of Clubs Three of Spades
Find card number in deck array If slot contains card number Queen of Clubs Five of Clubs
and print face and suit of card Print the face and suit of the Five of Hearts Ace of Diamonds
card

Fundamentals of Characters and Strings Fundamentals of Characters and Strings

Character constant String assignment


Integer value represented as character in single quotes
'z' is integer value of z Character array
122 in ASCII
char color[] = "blue";
Creates 5 element char array color
String last element is '\0'
Series of characters treated as single unit
Can include letters, digits, special characters +, -, * ... Variable of type char *
String literal (string constants) char *colorPtr = "blue";
Enclosed in double quotes, for example: Creates pointer colorPtr to letter b in string blue
blue somewhere in memory
"I like C++

Array of characters, ends with null character '\0' Alternative for character array
String is constant pointer char color[] = { b, l, u, e, \0 };
Pointer to strings first character
Like arrays

Fundamentals of Characters and Strings Fundamentals of Characters and Strings

Reading strings cin.getline


Read line of text
Assign input to character array word[ 20 ]
cin.getline( array, size, delimiter );
cin >> word
Copies input into specified array until either
One less than size is reached
Reads characters until whitespace or EOF delimiter character is input
String could exceed array size
Example
cin >> setw( 20 ) >> word; char sentence[ 80 ];
cin.getline( sentence, 80, '\n' );
Reads 19 characters (space reserved for '\0')
String Manipulation Functions of the String- String Manipulation Functions of the String-
handling Library handling Library
char *strcpy( char *s1, const char *s2 );
String handling library <cstring> Copies the string s2 into the character
array s1. The value of s1 is returned.
provides functions to
char *strncpy( char *s1, const char *s2, size_t n );
Manipulate string data Copies at most n characters of the string s2 into the character array s1. The value of s1 is
returned.
Compare strings
char *strcat( char *s1, const char *s2 );
Search strings for characters and other strings Appends the string s2 to the string s1. The first character of s2 overwrites the
terminating null character of s1. The value of s1 is returned.
Tokenize strings (separate strings into logical
pieces) char *strncat( char *s1, const char *s2, size_t n );
Appends at most n characters of string s2 to string s1. The first character of s2 overwrites
the terminating null character of s1. The value of s1 is returned.

int strcmp( const char *s1, const char *s2 );


Compares the string s1 with the string s2. The function returns a value of zero, less than
zero or greater than zero if s1 is equal to, less than or greater than s2, respectively.

String Manipulation Functions of the String- String Manipulation Functions of the String-
handling Library handling Library
int strncmp( const char *s1, const char *s2, size_t n ); Copying strings
Compares up to n characters of the string s1 with the string s2. The
function returns zero, less than zero or greater than zero if s1 is equal to, char *strcpy( char *s1, const char
less than or greater than s2, respectively. *s2 )
char *strtok( char *s1, const char *s2 ); Copies second argument into first argument
A sequence of calls to strtok breaks string s1 into tokenslogical pieces First argument must be large enough to store string and terminating
such as words in a line of textdelimited by characters contained in null character
string s2. The first call contains s1 as the first argument, and subsequent char *strncpy( char *s1, const char
calls to continue tokenizing the same string contain NULL as the first
argument. A pointer to the current token is returned by each call. If there *s2, size_t n )
are no more tokens when the function is called, NULL is returned. Specifies number of characters to be copied from string into
array
size_t strlen( const char *s ); Does not necessarily copy terminating null character
Determines the length of string s. The number of characters preceding the
terminating null character is returned.

1
2
3
//
// Using strcpy and strncpy.
#include <iostream>
<cstring> contains prototypes
for strcpy and strncpy. String Manipulation Functions of the
4
5
6
7
using std::cout;
using std::endl; String-handling Library
8 #include <cstring> // prototypes for strcpy and strncpy Copy entire string in array x into
9
10
11
int main()
{
array y. Concatenating strings
12
13
char x[] = "Happy Birthday to You";
char y[ 25 ];
char *strcat( char *s1, const char *s2 )
14
15
char z[ 15 ];
Copy first 14 characters of array x Appends second argument to first argument
16
17
strcpy( y, x ); // copy contents of x into y into array y. Note that this does First character of second argument replaces null character terminating
18 cout << "The string in array x is: " << x not write terminating null first argument
19 << "\nThe string in array y is: " << y << '\n';
character.
20
21 // copy first 14 characters of x into z Ensure first argument large enough to store concatenated result and
22
23
strncpy( z, x, 14 ); // does not copy null character
z[ 14 ] = '\0'; // append '\0' to z's contents null character
24
25 cout << "The string in array z is: " << z << endl; char *strncat( char *s1, const char *s2,
26
27 return 0; // indicates successful termination
Append terminating null
size_t n )
28
29 } // end main character. Appends specified number of characters from second argument to first
argument
Appends terminating null character to result

The string in array x is: Happy Birthday to You


The string in array y is: Happy Birthday to You
The string in array z is: Happy Birthday
1 // 26 cout << "\n\nAfter strncat(s3, s1, 6):\ns1 = " << s1
2 // Using strcat and strncat.
<cstring> contains prototypes 27 << "\ns3 = " << s3; Append s1 to s3.
3 #include <iostream> for strcat and strncat. 28
4 29 strcat( s3, s1 ); // concatenate s1 to s3
5 using std::cout; 30 cout << "\n\nAfter strcat(s3, s1):\ns1 = " << s1
6 using std::endl; 31 << "\ns3 = " << s3 << endl;
7 32
8 #include <cstring> // prototypes for strcat and strncat 33 return 0; // indicates successful termination
9 34
10 int main() 35 } // end main
11 {
12 char s1[ 20 ] = "Happy Append
"; s2 to s1.
s1 = Happy
13 char s2[] = "New Year "; s2 = New Year
14 char s3[ 40 ] = "";
15 After strcat(s1, s2):
16 cout << "s1 = " << s1 << "\ns2 = " << s2; s1 = Happy New Year
s2 = New Year
17
18 strcat( s1, s2 ); // concatenate s2 to s1 Append first 6 characters of s1 to After strncat(s3, s1, 6):
19 s3.
s1 = Happy New Year
20 cout << "\n\nAfter strcat(s1, s2):\ns1 = " << s1 s3 = Happy
21 << "\ns2 = " << s2;
22 After strcat(s3, s1):
23 // concatenate first 6 characters of s1 to s3 s1 = Happy New Year
s3 = Happy Happy New Year
24 strncat( s3, s1, 6 ); // places '\0' after last character
25

String Manipulation Functions of the String- String Manipulation Functions of the String-
handling Library handling Library
Comparing strings Comparing strings
Characters represented as numeric codes int strcmp( const char *s1, const char *s2 )
Compares character by character
Strings compared using numeric codes Returns
Character codes / character sets Zero if strings equal
ASCII Negative value if first string less than second string
American Standard Code for Information Interchage Positive value if first string greater than second string
EBCDIC int strncmp( const char *s1,
Extended Binary Coded Decimal Interchange Code const char *s2, size_t n )
Compares up to specified number of characters
Stops comparing if reaches null character in one of arguments

Compare up to 6 characters of s1
1
and s3.
// 26
2 // Using strcmp and strncmp. 27 cout << "\n\nstrncmp(s1, s3, 6) = " << setw( 2 )
3 #include <iostream>
28 << strncmp( s1, s3, 6 ) << "\nstrncmp(s1, s3, 7) = "
4 <cstring> contains prototypes
5 29 << setw( 2 ) << strncmp( s1, s3, 7 )
using std::cout; for strcmp and strncmp.
6 using std::endl; 30 << "\nstrncmp(s3, s1, 7) = "
7 31 << setw( 2 ) << strncmp( s3, s1, 7 ) << endl;
Compare up to 7 characters of s1
8 #include <iomanip> 32 and s3.
9 33 return 0; // indicates successful termination
10 using std::setw;
34 Compare up to 7 characters of s3
11
12 #include <cstring> // prototypes for strcmp and strncmp 35 } // end main and s1.
13
14 int main()
Compare s1 to s2.
15 {
16 char *s1 = "Happy New Year"; s1 = Happy New Year
17 char *s2 = "Happy New Year"; s2 = Happy New Year
18 char *s3 = "Happy Holidays";
s3 = Happy Holidays
19
20 cout << "s1 = " << s1 << "\ns2 = " << s2
21 << "\ns3 = " << s3 << "\n\nstrcmp(s1, s2) = " strcmp(s1, s2) = 0
22 << setw( 2 ) << strcmp( s1, s2 ) strcmp(s1, s3) = 1
23 << "\nstrcmp(s1, s3) = " << setw( 2 ) Compare s1 to s3. strcmp(s3, s1) = -1
24 << strcmp( s1, s3 ) << "\nstrcmp(s3, s1) = "
25 << setw( 2 ) << strcmp( s3, s1 );
strncmp(s1, s3, 6) = 0
strncmp(s1, s3, 7) = 1
Compare s3 to s1. strncmp(s3, s1, 7) = -1
String Manipulation Functions of the String- 1 //
2 // Using strtok.
handling Library 3
4
#include <iostream> <cstring> contains prototype
5 using std::cout; for strtok.
6 using std::endl;
7
Tokenizing 8 #include <cstring> // prototype for strtok
9
Breaking strings into tokens, separated by delimiting characters 10 int main()
11
Tokens usually logical units, such as words (separated by 12
{
char sentence[] = "This is a sentence with 7 tokens";
spaces) 13 char *tokenPtr; First call to strtok begins
14 tokenization.
"This is my string" has 4 word tokens (separated by 15 cout << "The string to be tokenized is:\n" << sentence
16
spaces) 17
<< "\n\nThe tokens are:\n\n";

char *strtok( char *s1, const char *s2 ) 18 // begin tokenization of sentence
19 tokenPtr = strtok( sentence, " " );
Multiple calls required 20
First call contains two arguments, string to be tokenized and string 21 // continue tokenizing sentence until tokenPtr becomes NULL
containing delimiting characters 22 while ( tokenPtr != NULL ) {
23 cout << tokenPtr << '\n';
Finds next delimiting character and replaces with null character 24 tokenPtr = strtok( NULL, " " ); // get next token
Subsequent calls continue tokenizing 25
Call with first argument NULL 26 } // end while
27
28 cout << "\nAfter strtok, sentence = " << sentence << endl;
29
30 return 0; // indicates successful termination
Subsequent calls to strtok with
31
32 } // end main NULL as first argument to
indicate continuation.

The string to be tokenized is:


String Manipulation Functions of the String-handling
This is a sentence with 7 tokens Library
The tokens are:

This
is
Determining string lengths
a size_t strlen( const char *s )
sentence
with Returns number of characters in string
7 Terminating null character not included in length
tokens

After strtok, sentence = This

1 //
2 // Using strlen.
3 #include <iostream>
4 <cstring> contains prototype
5 using std::cout; for strlen.
6 using std::endl;
7
8 #include <cstring> // prototype for strlen
9
10 int main()
11 {
12 char *string1 = "abcdefghijklmnopqrstuvwxyz";
13 char *string2 = "four";
14 char *string3 = "Boston";
15
16 cout << "The length of \"" << string1
17 << "\" is " << strlen( string1 ) Using strlen to
18 << "\nThe length of \"" << string2 determine length of strings.
19 << "\" is " << strlen( string2 )
20 << "\nThe length of \"" << string3
21 << "\" is " << strlen( string3 ) << endl;
22
23 return 0; // indicates successful termination
24
25 } // end main

The length of "abcdefghijklmnopqrstuvwxyz" is 26


The length of "four" is 4
The length of "Boston" is 6

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