C++ how to program05_第1頁(yè)
C++ how to program05_第2頁(yè)
C++ how to program05_第3頁(yè)
C++ how to program05_第4頁(yè)
C++ how to program05_第5頁(yè)
已閱讀5頁(yè),還剩33頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.1Chapter 5 - Pointers and StringsOutline5.1Introduction5.2Pointer Variable Declarations and Initialization5.3Pointer Operators5.4Calling Functions by Reference5.5Using the Const Qualifier

2、with Pointers5.6Bubble Sort Using Call-by-reference5.7Pointer Expressions and Pointer Arithmetic5.8The Relationship Between Pointers and Arrays5.9Arrays of Pointers5.10Case Study: A Card Shuffling and Dealing Simulation5.11Function Pointers5.12Introduction to Character and String Processing5.12.1 Fu

3、ndamentals of Characters and Strings5.12.2 String Manipulation Functions of theString-handling Library5.13Thinking About Objects: Interactions Among Objects 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.25.1Introduction Pointers Powerf

4、ul, but difficult to master Simulate call-by-reference Close relationship with arrays and strings 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.35.2Pointer Variable Declarations and Initialization Pointer variables Contain memory addre

5、sses as their values Normal variables contain a specific value (direct reference) Pointers contain the address of a variable that has a specific value (indirect reference) Indirection Referencing a pointer value Pointer declarations * indicates variable is a pointerint *myPtr; declares a pointer to

6、an int, a pointer of type int * Multiple pointers require multiple asterisksint *myPtr1, *myPtr2;count7countPtr count7 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.45.2Pointer Variable Declarations and Initialization Can declare point

7、ers to any data type Pointers initialization Initialized to 0, NULL, or an address 0 or NULL points to nothing 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.55.3Pointer Operators & (address operator) Returns the address of its oper

8、and Example int y = 5;int *yPtr;yPtr = &y; / yPtr gets address of y yPtr “points to” yyPtry5yptr500000600000y6000005address of y is value of yptr 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.65.3Pointer Operators * (indirection/de

9、referencing operator) Returns the value of what its operand points to *yPtr returns y (because yPtr points to y). * can be used to assign a value to a location in memory*yptr = 7; / changes y to 7 Dereferenced pointer (operand of *) must be an lvalue (no constants) * and & are inverses Cancel ea

10、ch other out*&myVar = myVar and&*yPtr = yPtr 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.Outline1. Declare variables2 Initialize variables3. PrintProgram Output1/ Fig. 5.4: fig05_04.cpp2/ Using the & and * operators3#incl

11、ude 45using std:cout;6using std:endl;78int main()910 int a; / a is an integer11 int *aPtr; / aPtr is a pointer to an integer1213 a = 7;14 aPtr = &a; / aPtr set to address of a1516 cout The address of a is &a17 nThe value of aPtr is aPtr;1819 cout nnThe value of a is a20 nThe value of *aPtr i

12、s *aPtr;2122 cout nnShowing that * and & are inverses of 23 each other.n&*aPtr = &*aPtr24 n*&aPtr = *&aPtr endl;25 return 0;26 The address of a is the value of aPtr. The * operator returns an alias to what its operand points to. aPtr points to a, so *aPtr returns a.Notice how * a

13、nd & are inverses The address of a is 006AFDF4The value of aPtr is 006AFDF4The value of a is 7The value of *aPtr is 7Showing that * and & are inverses of each other.&*aPtr = 006AFDF4*&aPtr = 006AFDF4 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates

14、, Inc. All rights reserved.85.4Calling Functions by Reference Call by reference with pointer arguments Pass address of argument using & operator Allows you to change actual location in memory Arrays are not passed with & because the array name is already a pointer * operator used as alias/ni

15、ckname for variable inside of function void doubleNum( int *number ) *number = 2 * ( *number ); *number used as nickname for the variable passed in When the function is called, must be passed an address doubleNum( &myNum ); 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel &

16、; Associates, Inc. All rights reserved.Outline1. Function prototype - takes a pointer to an int.1.1 Initialize variables2. Call function3. Define functionProgram Output1/ Fig. 5.7: fig05_07.cpp2/ Cube a variable using call-by-reference 3/ with a pointer argument4#include 56using std:cout;7using std:

17、endl;89void cubeByReference( int * ); / prototype1011 int main()12 13 int number = 5;1415 cout The original value of number is number;16 cubeByReference( &number );17 cout nThe new value of number is number endl;18 return 0;19 2021 void cubeByReference( int *nPtr )22 23 *nPtr = *nPtr * *nPtr * *

18、nPtr; / cube number in main24 Inside cubeByReference, *nPtr is used (*nPtr is number). The original value of number is 5The new value of number is 125Notice how the address of number is given - cubeByReference expects a pointer (an address of a variable). 2000 Deitel & Associates, Inc. All right

19、s reserved. 2000 Deitel & Associates, Inc. All rights reserved.105.5Using the Const Qualifier with Pointers const qualifier Variable cannot be changed const used when function does not need to change a variable Attempting to change a const variable is a compiler error const pointers Point to sam

20、e memory location Must be initialized when declaredint *const myPtr = &x; Constant pointer to a non-constant intconst int *myPtr = &x; Non-constant pointer to a constant intconst int *const Ptr = &x; Constant pointer to a constant int 2000 Deitel & Associates, Inc. All rights reserve

21、d. 2000 Deitel & Associates, Inc. All rights reserved.Outline1. Declare variables1.1 Declare const pointer to an int.2. Change *ptr (which is x).2.1 Attempt to change ptr.3. OutputProgram Output1/ Fig. 5.13: fig05_13.cpp2/ Attempting to modify a constant pointer to3/ non-constant data4#include 5

22、6int main()78 int x, y;910 int * const ptr = &x; / ptr is a constant pointer to an 11 / integer. An integer can be modified12 / through ptr, but ptr always points 13 / to the same memory location.14 *ptr = 7;15 ptr = &y;1617 return 0;18 Error E2024 Fig05_13.cpp 15: Cannot modify a const obje

23、ct in function main() Changing *ptr is allowed - x is not a constant.Changing ptr is an error - ptr is a constant pointer. 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.125.6Bubble Sort Using Call-by-reference Implement bubblesort usin

24、g pointers swap function must receive the address (using &) of the array elements array elements have call-by-value default Using pointers and the * operator, swap is able to switch the values of the actual array elements PsuedocodeInitialize array print data in original orderCall function bubbl

25、esortprint sorted arrayDefine bubblesort 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.135.6Bubble Sort Using Call-by-reference sizeof Returns size of operand in bytes For arrays, sizeof returns( the size of 1 element ) * ( number of e

26、lements ) if sizeof( int ) = 4, thenint myArray10;cout sizeof(myArray); will print 40 sizeof can be used with Variable names Type names Constant values 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.Outline1/ Fig. 5.15: fig05_15.cpp2/ T

27、his program puts values into an array, sorts the values into3/ ascending order, and prints the resulting array.4#include 56using std:cout;7using std:endl;89#include 1011 using std:setw;1213 void bubbleSort( int *, const int );1415 int main()16 17 const int arraySize = 10;18 int a arraySize = 2, 6, 4

28、, 8, 10, 12, 89, 68, 45, 37 ;19 int i;2021 cout Data items in original ordern;2223 for ( i = 0; i arraySize; i+ )24 cout setw( 4 ) a i ;2526 bubbleSort( a, arraySize ); / sort the array27 cout nData items in ascending ordern;2829 for ( i = 0; i arraySize; i+ )30 cout setw( 4 ) a i ;3132 cout endl;33

29、 return 0;34 1. Initialize array1.1 Declare variables2. Print array2.1 Call bubbleSort2.2 Print arrayBubblesort gets passed the address of array elements (pointers). The name of an array is a pointer. 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All righ

30、ts reserved.Outline3. Define bubbleSort3.1 Define swapProgram Output36 void bubbleSort( int *array, const int size )37 38 void swap( int * const, int * const );3940 for ( int pass = 0; pass size - 1; pass+ )4142 for ( int j = 0; j array j + 1 )45 swap( &array j , &array j + 1 );46 4748 void

31、swap( int * const element1Ptr, int * const element2Ptr )49 50 int hold = *element1Ptr;51 *element1Ptr = *element2Ptr;52 *element2Ptr = hold;53 swap takes pointers (addresses of array elements) and dereferences them to modify the original array elements. Data items in original order 2 6 4 8 10 12 89

32、68 45 37Data items in ascending order 2 4 6 8 10 12 37 45 68 89 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.165.7Pointer Expressions and Pointer Arithmetic Pointer arithmetic Increment/decrement pointer (+ or -) Add/subtract an integ

33、er to/from a pointer( + or += , - or -=) Pointers may be subtracted from each other Pointer arithmetic is meaningless unless performed on an 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 vPtr += 2; sets vPtr to 3008

34、vPtr points to v 2 pointer variable vPtrv0v1v2v4v330003004300830123016location 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.175.7Pointer Expressions and Pointer Arithmetic Subtracting pointers Returns the number of elements between tw

35、o addressesvPtr2 = v 2 ;vPtr = v 0 ;vPtr2 - vPtr = 2 Pointer comparison Test which pointer points to the higher numbered array element Test if a pointer points to 0 (NULL)if ( vPtr = 0 ) statement 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights r

36、eserved.185.7Pointer Expressions and Pointer Arithmetic Pointers assignment If not the same type, a cast operator must be used Exception: pointer to void (type void *) Generic pointer, represents any type No casting needed to convert a pointer to void pointer void pointers cannot be dereferenced 200

37、0 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.195.8The Relationship Between Pointers and Arrays Arrays and pointers closely related Array name like constant pointer Pointers can do array subscripting operations Having declared an array b

38、5 and a pointer bPtr bPtr is equal to bbptr = b bptr is equal to the address of the first element of bbptr = &b 0 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.205.8The Relationship Between Pointers and Arrays Accessing array eleme

39、nts with pointers Element b n can be accessed by *( bPtr + n ) Called pointer/offset notation Array itself can use pointer arithmetic. b 3 same as *(b + 3) Pointers can be subscripted (pointer/subscript notation) bPtr 3 same as b 3 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel

40、& Associates, Inc. All rights reserved.215.9Arrays of Pointers Arrays can contain pointers Commonly used to store an array of stringschar *suit 4 = Hearts, Diamonds, Clubs, Spades ; Each element of suit is a pointer to a char * (a string) The strings are not in the array, only pointers to the st

41、rings are in the array suit array has a fixed size, but strings can be of any sizesuit3suit2suit1suit0Hearts 0Diamonds 0Clubs 0Spades 0 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.225.10Case Study: A Card Shuffling and Dealing Simula

42、tion Card shuffling program Use an array of pointers to strings, to store suit names Use a double scripted array (suit by value) Place 1-52 into the array to specify the order in which the cards are dealtdeck212 represents the King of ClubsHeartsDiamondsClubsSpades0123AceTwoThree FourFiveSixSeven Ei

43、ght NineTenJackQueen King0123456789101112ClubsKing 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.235.10Case Study: A Card Shuffling and Dealing Simulation Pseudocode for shuffling and dealingsimulationFor each of the 52 cardsPlace card

44、 number in randomly selected unoccupied slot of deck For each of the 52 cardsFind card number in deck array and print face and suit of card Choose slot of deck randomlyWhile chosen slot of deck has been previously chosenChoose slot of deck randomlyPlace card number in chosen slot of deck For each sl

45、ot of the deck arrayIf slot contains card number Print the face and suit of the card Second refinementThird refinementFirst refinementInitialize the suit arrayInitialize the face arrayInitialize the deck arrayShuffle the deckDeal 52 cards 2000 Deitel & Associates, Inc. All rights reserved. 2000

46、Deitel & Associates, Inc. All rights reserved.Outline1. Initialize suit and face arrays1.1 Initialize deck array2. Call function shuffle2.1 Call function deal1/ Fig. 5.24: fig05_24.cpp2/ Card shuffling dealing program3#include 45using std:cout;6using std:ios;78#include 910 using std:setw;11 usin

47、g std:setiosflags;1213 #include 14 #include 1516 void shuffle( int 13 );17 void deal( const int 13 , const char *, const char * );1819 int main()20 21 const char *suit 4 = 22 Hearts, Diamonds, Clubs, Spades ;23 const char *face 13 = 24 Ace, Deuce, Three, Four,25 Five, Six, Seven, Eight,26 Nine, Ten,

48、 Jack, Queen, King ;27 int deck 4 13 = 0 ;2829 srand( time( 0 ) );3031 shuffle( deck );32 deal( deck, face, suit );33 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.Outline3. Define functions 34 return 0;35 3637 void shuffle( int wDeck

49、13 )38 39 int row, column;4041 for ( int card = 1; card = 52; card+ ) 42 do 43 row = rand() % 4;44 column = rand() % 13;45 while( wDeck row column != 0 );4647 wDeck row column = card;48 49 5051 void deal( const int wDeck 13 , const char *wFace,52 const char *wSuit )53 54 for ( int card = 1; card = 5

50、2; card+ )5556 for ( int row = 0; row = 3; row+ )5758 for ( int column = 0; column = 12; column+ )5960 if ( wDeck row column = card )61 cout setw( 5 ) setiosflags( ios:right )62 wFace column of 63 setw( 8 ) setiosflags( ios:left )64 wSuit row 65 ( card % 2 = 0 ? n : t );66 The numbers 1-52 are rando

51、mly placed into the deck array.Searches deck for the card number, then prints the face and suit. 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.OutlineProgram OutputSix of Clubs Seven of Diamonds Ace of Spades Ace of Diamonds Ace of Hea

52、rts Queen of DiamondsQueen of Clubs Seven of Hearts Ten of Hearts Deuce of Clubs Ten of Spades Three of Spades Ten of Diamonds Four of Spades Four of Diamonds Ten of Clubs Six of Diamonds Six of SpadesEight of Hearts Three of Diamonds Nine of Hearts Three of HeartsDeuce of Spades Six of Hearts Five

53、of Clubs Eight of ClubsDeuce of Diamonds Eight of Spades Five of Spades King of Clubs King of Diamonds Jack of SpadesDeuce of Hearts Queen of Hearts Ace of Clubs King of SpadesThree of Clubs King of Hearts Nine of Clubs Nine of Spades Four of Hearts Queen of SpadesEight of Diamonds Nine of Diamonds

54、Jack of Diamonds Seven of Clubs Five of Hearts Five of Diamonds Four of Clubs Jack of Hearts Jack of Clubs Seven of Spades 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.275.11Function Pointers Pointers to functions Contain the address

55、of the function Similar to how an array name is the address of its first element Function name is starting address of code that defines function Function pointers can be Passed to functions Stored in arrays Assigned to other function pointers 2000 Deitel & Associates, Inc. All rights reserved. 2

56、000 Deitel & Associates, Inc. All rights reserved.285.11Function Pointers Example: bubblesort Function bubble takes a function pointer The function determines whether the the array is sorted into ascending or descending sorting The argument in bubble for the function pointerbool ( *compare )( in

57、t, int )tells bubble to expect a pointer to a function that takes two ints and returns a bool If the parentheses were left outbool *compare( int, int ) would declare a function that receives two integers and returns a pointer to a bool 2000 Deitel & Associates, Inc. All rights reserved. 2000 Dei

58、tel & Associates, Inc. All rights reserved.Outline1. Initialize array2. Prompt for ascending or descending sorting2.1 Put appropriate function pointer into bubblesort2.2 Call bubble3. Print results1/ Fig. 5.26: fig05_26.cpp2/ Multipurpose sorting program using function pointers3#include 45using

59、std:cout;6using std:cin;7using std:endl;89#include 1011 using std:setw;1213 void bubble( int , const int, bool (*)( int, int ) );14 bool ascending( int, int );15 bool descending( int, int );1617 int main()18 19 const int arraySize = 10;20 int order, 21 counter,22 a arraySize = 2, 6, 4, 8, 10, 12, 89

60、, 68, 45, 37 ;2324 cout Enter 1 to sort in ascending order,n 25 order;27 cout nData items in original ordern;28 29 for ( counter = 0; counter arraySize; counter+ )30 cout setw( 4 ) a counter ;3132 if ( order = 1 ) 33 bubble( a, arraySize, ascending );34 cout nData items in ascending ordern;Notice th

61、e function pointer parameter. 2000 Deitel & Associates, Inc. All rights reserved. 2000 Deitel & Associates, Inc. All rights reserved.Outline3.1 Define functions35 36 else 37 bubble( a, arraySize, descending );38 cout nData items in descending ordern;39 4041 for ( counter = 0; counter arraySize; counter+ )42 cout setw( 4 ) a counter ;4344 co

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論