Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Pointers
Pointer variables
count 7
Contain memory addresses as values Normally, variable contains specific value (direct reference) Pointers contain address of variable that has specific countPtr count value (indirect reference)
Indirection
Pointer declarations
declares pointer to int, pointer of type int * Multiple pointers require multiple asterisks
int *myPtr1, *myPtr2;
Can
&
(address operator)
Returns memory address of its operand Example
int y = 5; int *yPtr; yPtr = &y; // yPtr gets address of y
yPtr points to y
y 5 yptr 500000 600000 y
yPtr
600000
(indirection/dereferencing operator)
*yPtr returns y (because yPtr points to y). dereferenced pointer is lvalue
*yptr = 9; // assigns 9 to y
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
// code 1 // Using the & and * operators. #include <iostream> using std::cout; using std::endl; int main() { int a; // a is an integer int *aPtr; // aPtr is a pointer to an integer a = 7; aPtr = &a; // aPtr assigned address of a cout << "The address of a is " << &a << "\nThe value of aPtr is " << aPtr; cout << "\n\nThe value of a is " << a << "\nThe value of *aPtr is " << *aPtr; cout << "\n\nShowing that * and & are inverses of " << "each other.\n&*aPtr = " << &*aPtr << "\n*&aPtr = " << *&aPtr << endl;
* and & are inverses 0012FED4 The address of a is of each other aPtr is 0012FED4 The value of
The value of a is 7 The value of *aPtr is 7 Showing that * and & are inverses of each other. &*aPtr = 0012FED4 *&aPtr = 0012FED4 7
can return one value from function Arguments passed to function using reference arguments
return
Pass-by-reference
Simulate pass-by-reference
Use pointers and indirection operator
Pass address of argument using & operator Arrays not passed with & because array name already pointer * operator used with alias/nickname for variable inside of function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// code 2 // Cube a variable using pass-by-value. #include <iostream> using std::cout; using std::endl; int cubeByValue( int ); // prototype int main() { int number = 5; cout << "The original value of number is " << number; // pass number by value to cubeByValue number = cubeByValue( number );
19
20 21 22 23 24 25 26 27 28 29 30
cout << "\nThe new value of number is " << number << endl;
return 0; // indicates successful termination } // end main // calculate and return cube of integer argument int cubeByValue( int n ) { return n * n * n; // cube local variable n and return result } // end function cubeByValue
4 6 7 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#include <iostream> using std::cout; using std::endl; void cubeByReference( int * ); // prototype int main() { int number = 5; cout << "The original value of number is " << number; // pass address of number to cubeByReference cubeByReference( &number ); cout << "\nThe new value of number is " << number << endl; return 0; // indicates successful termination } // end main // calculate cube of *nPtr; modifies variable number in main void cubeByReference( int *nPtr ) { *nPtr = *nPtr * *nPtr * *nPtr; // cube *nPtr
cubeByReference receives address of intvalue of number is The original variable, The new value of number is 125 i.e., pointer to an int
11
Write
1-12
const
qualifier
Value of variable should not be modified const used when function does not need to change a variable
Principle
of least privilege
Four
Nonconstant pointer to constant data Constant pointer to nonconstant data Constant pointer to constant data
Convert
void convertToUppercase( char *sPtr ) { while ( *sPtr != '\0' ) { // current character is not '\0' Parameter sPtr nonconstant if ( islower( *sPtr ) ) // if character is lowercase, pointer to nonconstant data *sPtr = toupper( *sPtr ); // convert to uppercase Function islower returns ++sPtr; // move sPtr to nexttrue if character is character in string } // end while lowercase } // end function convertToUppercase
1-14
// Converting lowercase letters to uppercase letters 3 4 // using a non-constant pointer to non-constant data. #include <iostream>
6 7 9 10 11 13 14 15 17 18 19 20 22 24 25 27 28 29 30 31 32 33 34 35 36 37 38
char phrase[] = "characters and $32.98"; cout << "The phrase before conversion is: " << phrase; convertToUppercase( phrase ); cout << "\nThe phrase after conversion is: " << phrase << endl; return 0; // indicates successful termination } // end main 26 // convert string to uppercase letters void convertToUppercase( char *sPtr ) { while ( *sPtr != '\0' ) { // current character is not '\0'
if ( islower( *sPtr ) ) // if character is lowercase, *sPtr = toupper( *sPtr ); // convert to uppercase ++sPtr; // move sPtr to next character in string
Function islower returns true if character is operator ++ applied to lowercase When phrase before conversion is: The } // end while pointer that points to conversion is: array, The phrase after memory address stored in } // end function convertToUppercase pointer modified to point to next element of array.
15
1-16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 23 24 25 26 27 28 29 30
// code 5 // Printing a string one character at a time using // a non-constant pointer to constant data. #include <iostream> using std::cout; using std::endl; void printCharacters( const char * ); int main() { char phrase[] = "print characters of a string"; cout << "The string is:\n"; printCharacters( phrase ); cout << endl; return 0; // indicates successful termination } // end main // sPtr cannot modify the character to which it points, The string is: // i.e., sPtr is a "read-only" pointer print characters of a string void printCharacters( const char *sPtr ) { for ( ; *sPtr != '\0'; sPtr++ ) // no initialization sPtr is nonconstant pointer cout << *sPtr; to constant data; cannot } // end function printCharacters
Attempting
1-18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// code 6 // Attempting to modify data through a // non-constant pointer to constant data. void f( const int * ); // prototype int main() { int y;
address of int variable y to attempt illegal modification. Attempt to modify const object pointed to by xPtr.
// xPtr cannot modify the value of the variable // to which it points void f( const int *xPtr ) {
const
pointers
Always point to same memory location Default for array name Must be initialized when declared
20
1 2 3 4 5 6 7 8
// code 7 // Attempting to modify a constant pointer to // non-constant data. int main() { int x, y;
ptr // ptr is a constant pointer to an integer that canis constant pointer to 10 // be modified through ptr, but ptr always points to the integer. Can modify x (pointed to by 11 // same memory location. 12 int * const ptr = &x; ptr) since x not constant. Cannot modify ptr to point 13 to new address since ptr is 14 *ptr = 7; // allowed: *ptr is not const constant. 15 ptr = &y; // error: ptr is const; cannot assign new address 16 17 return 0; // indicates successful termination Line 15 generates compiler 18 error by attempting to assign 19 } // end main new address to constant pointer.
21
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// code 8 // Attempting to modify a constant pointer to constant data. #include <iostream> using std::cout; using std::endl; int main() { int x = 5, y; // ptr is a constant pointer to a constant integer. ptr is constant pointer // ptr always points to the same location; the integer integer constant. // at that location cannot be modified. const int *const ptr = &x;
to
Cannot modify x (pointed to cout << *ptr << endl; by ptr) since *ptrto point Cannot modify ptr declared constant. to new address since ptr is *ptr = 7; // error: *ptr is const; cannot assign new value constant. ptr = &y; // error: ptr is const; cannot assign new address
return 0; // indicates successful termination } // end main
error C2166: l-value specifies const object error C2166: l-value specifies const object
Line 19 generates compiler Line by attempting to modify error 20 generates compiler error by object. constant attempting to assign new address to constant pointer.
22
sizeof
Unary operator returns size of operand in bytes For arrays, sizeof returns
( size of 1 element ) * ( number of elements )
will print 40
sizeof
1 2 3
// code 10 // Sizeof operator when used on an array name // returns the number of bytes in the array.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 21 22 23 24 26 27 28 29 30
#include <iostream>
using std::cout; using std::endl; size_t getSize( double * ); // prototype
Operator sizeof applied to an array returns total number cout << "The number of bytes in the array is " of bytes in array.
<< sizeof( array );
return 0; // indicates successful termination } // end main 25 // return size of ptr size_t getSize( double *ptr ) {
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 meaningless unless performed on pointer to array
3000
3004
3008
3012
3016
Subtracting
pointers
Pointer
assignment
Pointer can be assigned to another pointer if both of same type If not same type, cast operator must be used Exception: Void Pointer: pointer to void (type void *)
26
Addresses
bPtr[ 3 ] same as b[ 3 ]
27
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <iostream>
using std::cout; using std::endl; int main() { int b[] = { 10, 20, 30, 40 }; int *bPtr = b; // set bPtr to point to array b // output array b using array subscript notation cout << "Array b printed with:\n" << "Array subscript notation\n"; for ( int i = 0; i < 4; i++ ) cout << "b[" << i << "] = " << b[ i ] << '\n'; // output array b using the array name and // pointer/offset notation cout << "\nPointer/offset notation where " << "the pointer is the array name\n";
notation
28
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
for ( int offset1 = 0; offset1 < 4; offset1++ ) cout << "*(b + " << offset1 << ") = " << *( b + offset1 ) << '\n';
Using array name and // output array b using bPtr and array subscript notation pointer/offset notation.
cout << "\nPointer subscript notation\n"; for ( int j = 0; j < 4; j++ ) cout << "bPtr[" << j << "] = " << bPtr[ j ] << '\n'; cout << "\nPointer/offset notation\n"; // output array b using bPtr and pointer/offset notation for ( int offset2 = 0; offset2 < 4; offset2++ ) cout << "*(bPtr + " << offset2 << ") = " << *( bPtr + offset2 ) << '\n'; return 0; // indicates successful termination } // end main
29
Array b printed with: Array subscript notation b[0] = 10 b[1] = 20 b[2] = 30 b[3] = 40 Pointer/offset notation where the pointer is the array name *(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
30
Each element of suit points to char * (a string) Array does not store strings, only pointers to strings
H D C S e i l p a a u a r m b d t o s e s n \0 s \0 \0 d s \0
suit[0]
suit[1]
suit[2] suit[3]
suit array has fixed size, but strings can be of any size
31
Character constant
String
122 in ASCII
Series of characters treated as single unit Can include letters, digits, special characters +, -, * ... String literal (string constants)
Array of characters, ends with null character '\0' String is constant pointer
32
String
assignment
Character array
char color[] = "blue"; Creates 5 element char array color
char color[] = { b, l, u, e, \0 };
33
Reading
strings
34
cin.getline
Read line of text cin.getline( array, size, delimiter ); Copies input into specified array until either
Example
char sentence[ 80 ]; cin.getline( sentence, 80, '\n' );
35
String
36
char *strcpy( char *s1, const char *s2 ); char *strncpy( char *s1, const char *s2, size_t n ); char *strcat( char *s1, const char *s2 );
Copies the string s2 into the character array s1. The value of s1 is returned. Copies at most n characters of the string s2 into the character array s1. The value of s1 is returned. Appends a copy of 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. 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.
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.
37
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, less than or greater than s2, respectively.
A sequence of calls to strtok breaks string s1 into tokenslogical pieces such as words in a line of textdelimited by characters contained in string s2. The first call contains s1 as the first argument, and subsequent 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 are no more tokens when the function is called, NULL is returned. Determines the length of string s. The number of characters preceding the terminating null character is returned.
38
Copying
strings
Copies second argument into first argument First argument must be large enough to store string and terminating null character
Specifies number of characters to be copied from string into array Does not necessarily copy terminating null character
39
We
We
want to copy only 8 characters from car name 1 into car name 2.
#include <iostream> using namespace std; int main() { char CarName1[ ] = "Ford Escort"; char CarName2[ ] = "Toyota 4-Runner"; cout << "The String Copy Operation"; cout << "\nFirst Car: " << CarName1; cout << "\nSecond Car: " << CarName2;
Second Car: Toyota 4-Runner cout << "\n\nAfter using strncpy() for 8 characters"; cout << "\nFirst Car: " << CarName1; cout << "\nSecond Car: " << CarName2 << endl;
return 0;
Concatenating
strings
Appends second argument to first argument First character of second argument replaces null character terminating first argument Ensure first argument large enough to store concatenated result and null character
Appends specified number of characters from second argument to first argument Appends terminating null character to result
42
1 2 3
4 using std::endl; 5 #include <cstring> // prototypes 6 7 int main() 8 { 9 char s1[ 20 ] = "Happy "; 10 char s2[] = "New Year "; 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 char s3[ 40 ] = "";
<cstring> contains prototypes for strcat and strncat. for strcat and strncat
43
Append s2 to s1.
// concatenate s2 to s1
cout << "s1 = " << s1 << "\ns2 = " << s2; strcat( s1, s2 );
cout << "\n\nAfter strcat(s1, s2):\ns1 = " << s1 << "\ns2 = " << s2;
cout << "\n\nAfter strncat(s3, s1, 6):\ns1 = " << s1 << "\ns3 = " << s3; strcat( cout << << return 0; s3, s1 ); // concatenate s1 to s3 "\n\nAfter strcat(s3, s1):\ns1 = " << s1 "\ns3 = " << s3 << endl; } // indicates successful termination
Append s1 to s3.
s1 = Happy New Year s2 = New Year After strncat(s3, s1, 6): s1 = Happy New Year s3 = Happy After strcat(s3, s1): s1 = Happy New Year s3 = Happy Happy New Year
We
Make: which has the string Ford Model: which has the name Explorer
int main() {
strcat(Make, Model);
cout << "\n\nAfter concatenating, Make = " << Make << endl; return 0;
}
Originally, Make = Ford
Comparing
strings
ASCII American Standard Code for Information Interchange EBCDIC Extended Binary Coded Decimal Interchange Code
46
Comparing strings
Compares character by character Returns Zero if strings equal Negative value if first string less than second string Positive value if first string greater than second string
Compares up to specified number of characters Stops comparing if reaches null character in one of arguments
47
2 3 5 6 8 9 10 12 13 14 15 16 17 18 19 20 21 22
// Using strcmp and strncmp. #include <iostream> using std::cout; using std::endl; #include <iomanip> using std::setw; #include <cstring> int main() { char *s1 = "Happy New Year"; char *s2 = "Happy New Year"; char *s3 = "Happy Holiday"; cout << "s1 = " << s1 << "\ns2 = " << s2 << "\ns3 = " << s3 << "\n\nstrcmp(s1, s2) = " << setw( 2 ) << strcmp( s1, s2 )
48
23 << "\nstrcmp(s1, s3) = " << setw( 2 ) 24 << strcmp( s1, s3 ) << "\nstrcmp(s3, s1) = " << setw( 2 ) << strcmp( s3, s1 ); cout << "\n\nstrncmp(s1, s3, 6) = " << setw( 2 ) 28 29 30 31 32 33 34 35 << <<
<< << setw( 2 ) << strncmp( s3, s1, 7 ) << endl; return 0; } // end main // indicates successful termination
Compare up characters up s1 7 Compare of to and strncmp( s1, s3, 6 ) << "\nstrncmp(s1, s3, 7) = " s3. characters of strcmp(s1, s2) s1 and setw( 2 ) << strncmp( s1, s3, 7 ) Compare up to 7 s3) strcmp(s1, s3. characters of s3 and "\nstrncmp(s3, s1, 7) = " s1.
Tokenizing
Breaking strings into tokens, separated by delimiting characters Tokens usually logical units, such as words (separated by spaces) "This is my string" has 4 word tokens (separated by spaces) char *strtok( char *s1, const char *s2 )
Multiple calls required First call contains two arguments, string to be tokenized and string containing delimiting characters
1 2 3 4 5 6 7 8 9 10
// code 17 // Using strtok. #include <iostream> using std::cout; using std::endl; #include <cstring> int main()
50
11
12 13 14 15 16 17 18 19 20 22 23 24 25 26 27 28 29 30 31 32
{
char sentence[] = "This is a sentence with 7 tokens"; char *tokenPtr; cout << "The string to be tokenized is:\n" << sentence << "\n\nThe tokens are:\n\n"; // begin tokenization of sentence tokenPtr = strtok( sentence, " " ); 21 while ( tokenPtr != NULL ) { cout << tokenPtr << '\n'; tokenPtr = strtok( NULL, " " ); } // end while cout << "\nAfter strtok, sentence = " << sentence << endl; return 0; } // end main // indicates successful termination // get next token
The string to be tokenized is: This is a sentence with 7 tokens The tokens are: This is a sentence
Subsequent calls to with strtok7with NULL as tokens first argument to indicateAfter strtok, sentence continuation.
= This
Determining
string lengths
51
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
// code 18 // Using strlen. #include <iostream> using std::cout; using std::endl; #include <cstring> int main() { char *string1 = "abcdefghijklmnopqrstuvwxyz"; char *string2 = "four"; char *string3 = "Boston"; cout << "The length of \"" << string1 << "\" is " << strlen( string1 ) << "\nThe length of \"" << string2 << "\" is " << strlen( string2 ) << "\nThe length of \"" << string3 << "\" is " << strlen( string3 ) << endl; return 0; } // end main // indicates successful termination
52
Write
#include <iostream> using namespace std; int main() { char *School = MAJU"; int Length = strlen(School); cout << "The length of \"" << School << "\" is " << Length << " characters\n\n"; return 0; } The length of MAJU" is 4 characters
Write
1-55
#include<iostream.h>
#include<conio.h> #include<stdio.h> int main( ) { clrscr( ); char str[80]; cout<<"Enter a string:"; cin.getline( str, 80, '\n' ); for(int l=0; str[l]!='\0';l++); for(int i=l-1;i>=0;i--) cout<<str[i]; getch(); return 0; }
1-56
Write
1-57
#include<iostream.h> #include<conio.h> #include<stdio.h> int main( ) { clrscr( ); char str[80]; int words=0; cout<<"Enter a string:"; gets(str); for(int i=0;str[i]!='\0';i++) { if (str[i]==' ') words++; //Checking for spaces } cout<<"The number of words="<<words+1<<endl; getch(); return 0; }
1-58
Write
1-59
1-60
Write
a program to find a substring within a string. If found display its starting position.
1-61
1-62
1-63
Write
1-64
Use
1-65
Write a program that reads a string from a user and then prints out all the rotations of the string. For example, the rotations of the word space are
Note: You have to write a generalized program, which must work for every string. You may assume that maximum size of the string is 50 characters.
1-66