C++程序設計英文課件:Ch8 Pointers and Pointer-Based Strings_第1頁
C++程序設計英文課件:Ch8 Pointers and Pointer-Based Strings_第2頁
C++程序設計英文課件:Ch8 Pointers and Pointer-Based Strings_第3頁
C++程序設計英文課件:Ch8 Pointers and Pointer-Based Strings_第4頁
C++程序設計英文課件:Ch8 Pointers and Pointer-Based Strings_第5頁
已閱讀5頁,還剩141頁未讀, 繼續(xù)免費閱讀

付費下載

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領

文檔簡介

18Pointersand

Pointer-Based

Strings

2OBJECTIVESInthischapteryou’lllearn:Whatpointersare.Thesimilaritiesanddifferencesbetweenpointersandreferencesandwhentouseeach.Tousepointerstopassargumentstofunctionsbyreference.Tousepointer-basedC-stylestrings.Thecloserelationshipsamongpointers,arraysandC-stylestrings.Tousepointerstofunctions.TodeclareandusearraysofC-stylestrings.38.1 Introduction8.2 PointerVariableDeclarationsandInitialization8.3 PointerOperators8.4 PassingArgumentstoFunctionsbyReferencewithPointers8.5 UsingconstwithPointers8.6 SelectionSortUsingPass-by-Reference8.7

sizeofOperators8.7 PointerExpressionsandPointerArithmetic8.9 RelationshipBetweenPointersandArrays8.10 ArraysofPointers8.11 CaseStudy:CardShufflingandDealingSimulation8.12 FunctionPointers8.13 IntroductiontoPointer-BasedStringProcessing

8.13.1 FundamentalsofCharactersandPointer-BasedStrings

8.13.2 StringManipulationFunctionsoftheString-Handling Library8.14 Wrap-Up48.1IntroductionPointersPowerful,butdifficulttomasterCanbeusedtoperformpass-by-referenceCanbeusedtocreateandmanipulatedynamicdatastructuresCloserelationshipwitharraysandstringschar*pointer-basedstrings58.2 PointerVariableDeclarationsandInitializationPointervariablesContainmemoryaddressesasvaluesNormally,variablecontainsspecificvalue(directreference)Pointerscontainaddressofvariablethathasspecificvalue(indirectreference)IndirectionReferencingvaluethroughpointer68.2 PointerVariableDeclarationsandInitialization(Cont.)Pointerdeclarations*indicatesvariableisapointerExampleint*myPtr;Declarespointertoint,oftypeint

*Multiplepointersrequiremultipleasterisksint*myPtr1,*myPtr2;PointerinitializationInitializedto0,NULL,oranaddress0orNULLpointstonothing(nullpointer)7CommonProgrammingError8.1Assumingthatthe*usedtodeclareapointerdistributestoallvariablenamesinadeclaration’scomma-separatedlistofvariablescanleadtoerrors.Eachpointermustbedeclaredwiththe*prefixedtothename(eitherwithorwithoutaspaceinbetween—thecompilerignoresthespace).Declaringonlyonevariableperdeclarationhelpsavoidthesetypesoferrorsandimprovesprogramreadability.8GoodProgrammingPractice8.1Althoughitisnotarequirement,includingthelettersPtrinpointervariablenamesmakesitclearthatthesevariablesarepointersandthattheymustbehandledappropriately.9Fig.8.1

|Directlyandindirectlyreferencingavariable.10Error-PreventionTip8.1Initializepointerstopreventpointingtounknownoruninitializedareasofmemory.118.3 PointerOperators Addressoperator(&)ReturnsmemoryaddressofitsoperandExampleinty=5;

int*yPtr;

yPtr=&y;

assignstheaddressofvariableytopointervariableyPtrVariableyPtr“pointsto”yyPtrindirectlyreferencesvariabley’svalue12Fig.8.2

|Graphicalrepresentationofapointerpointingtoavariableinmemory.138.3 PointerOperators(Cont.)*operatorAlsocalledindirectionoperatorordereferencingoperatorReturnssynonymfortheobjectitsoperandpointsto*yPtrreturnsy(becauseyPtrpointstoy)Dereferencedpointerisanlvalue*yptr=9;*and&areinversesofeachotherWill“canceloneanotherout”whenappliedconsecutivelyineitherorder14Fig.8.3

|RepresentationofyandyPtrinmemory.15CommonProgrammingError8.2Dereferencingapointerthathasnotbeenproperlyinitializedorthathasnotbeenassignedtopointtoaspecificlocationinmemorycouldcauseafatalexecution-timeerror,oritcouldaccidentallymodifyimportantdataandallowtheprogramtoruntocompletion,possiblywithincorrectresults.16CommonProgrammingError8.3Anattempttodereferenceavariablethatisnotapointerisacompilationerror.17CommonProgrammingError8.4Dereferencinganullpointerisnormallyafatalexecution-timeerror.18PortabilityTip8.1Theformatinwhichapointerisoutputiscompilerdependent.Somesystemsoutputpointervaluesashexadecimalintegers,someusedecimalintegersandsomeuseotherformats.19abcdef101010121014101810221023344.58.6xypapbpcpdpepf20022006`20102014201820222026101010121014101810221023&a3paa,*pa&b4pbb,*pb&c4.5pcc,*pc&d8.6pdd,*pd&expee,*pe&fypff,*pf20Outlinefig08_04.cpp

(1of2)VariableaPtrisapointtoanintInitializeaPtrwiththeaddressofvariablea21Outlinefig08_04.cpp

(2of2)*and&areinversesofeachotherAddressofaandthevalueofaPtrareidentical*and&areinverses;sameresultwhenbothareappliedtoaPtrValueofaandthedereferencedaPtrareidentical22Fig.8.5

|Operatorprecedenceandassociativity.238.4PassingArgumentstoFunctionsbyReferencewithPointersThreewaystopassargumentstoafunctionPass-by-valuePass-by-referencewithreferenceargumentsPass-by-referencewithpointerargumentsAfunctioncanreturnonlyonevalueArgumentspassedtoafunctionusingreferenceargumentsFunctioncanmodifyoriginalvaluesofargumentsMorethanonevalue“returned”248.4PassingArgumentstoFunctionsbyReferencewithPointers(Cont.)Pass-by-referencewithpointerargumentsSimulatespass-by-referenceUsepointersandindirectionoperatorPassaddressofargumentusing&operatorArraysnotpassedwith&becausearraynameisalreadyapointer*operatorusedasalias/nicknameforvariableinsideoffunction25Outlinefig08_06.cpp

(1of1)Passnumberbyvalue;resultreturnedbycubeByValuecubeByValuereceivesparameterpassed-by-valueCubeslocalvariablenandreturntheresult26CommonProgrammingError8.5Notdereferencingapointerwhenitisnecessarytodosotoobtainthevaluetowhichthepointerpointsisanerror.27Outlinefig08_07.cpp

(1of1)PrototypeindicatesparameterisapointertoanintApplyaddressoperator&topassaddressofnumbertocubeByReferencecubeByReferencemodifiesvariablenumbercubeByReferencereceivesaddressofanintvariable,i.e.,apointertoanintModifyandaccessintvariableusingindirectionoperator*28SoftwareEngineeringObservation8.1Usepass-by-valuetopassargumentstoafunctionunlessthecallerexplicitlyrequiresthatthecalledfunctiondirectlymodifythevalueoftheargumentvariableinthecaller.Thisisanotherexampleoftheprincipleofleastprivilege.29Fig.8.8

|Pass-by-valueanalysisoftheprogramofFig.

8.6.30Fig.8.9

|Pass-by-referenceanalysis(withapointerargument)oftheprogramofFig.

8.7.318.5UsingconstwithPointersconstqualifierIndicatesthatvalueofvariableshouldnotbemodifiedconstusedwhenfunctiondoesnotneedtochangethevariable’svaluePrincipleofleastprivilegeAwardfunctionenoughaccesstoaccomplishtask,butnomoreExampleAfunctionthatprintstheelementsofanarray,takesarrayandintindicatinglengthArraycontentsarenotchanged–shouldbeconstArraylengthisnotchanged–shouldbeconst32SoftwareEngineeringObservation8.2Ifavaluedoesnot(orshouldnot)changeinthebodyofafunctiontowhichitispassed,theparametershouldbedeclaredconsttoensurethatitisnotaccidentallymodified.33Error-PreventionTip8.2Beforeusingafunction,checkitsfunctionprototypetodeterminetheparametersthatitcanmodify.Pointer’sselfincreacingint*pi;inta[5]={1,3,5,7,9};pi=a;pi++;//whatdoesthismean?3435Outlinefig08_10.cpp

(1of2)ParameterisanonconstantpointertononconstantdataconvertToUppercasemodifiesvariablephrase36Outlinefig08_10.cpp

(2of2)ParametersPtrisanonconstantpointertononconstantdataFunctionislowerreturnstrueifthecharacterislowercaseFunctiontoupperreturnscorrespondinguppercasecharacteriforiginalcharacterislowercase;otherwisetoupperreturnstheoriginalcharacterModifythememoryaddressstoredinsPtrtopointtothenextelementofthearray378.5UsingconstwithPointers(Cont.)FourwaystopasspointertofunctionNonconstantpointertononconstantdataHighestamountofaccessDatacanbemodifiedthroughthedereferencedpointerPointercanbemodifiedtopointtootherdataPointerarithmeticOperator++movesarraypointertothenextelementItsdeclarationdoesnotincludeconstqualifier388.5UsingconstwithPointers(Cont.)Fourwaystopasspointertofunction(Cont.)NonconstantpointertoconstantdataPointercanbemodifiedtopointtoanyappropriatedataitemDatacannotbemodifiedthroughthispointerProvidestheperformanceofpass-by-referenceandtheprotectionofpass-by-value39Outlinefig08_11.cpp

(1of1)ParameterisanonconstantpointertoconstantdataPasspointerphrasetofunctionprintCharacterssPtrisanonconstantpointertoconstantdata;itcannotmodifythecharactertowhichitpointsIncrementsPtrtopointtothenextcharacter40Outlinefig08_12.cpp

(1of2)ParameterisanonconstantpointertoconstantdataPasstheaddressofintvariableytoattemptanillegalmodification41Outlinefig08_12.cpp

(2of2)AttempttomodifyaconstobjectpointedtobyxPtrErrorproducedwhenattemptingtocompile42PerformanceTip8.1Iftheydonotneedtobemodifiedbythecalledfunction,passlargeobjectsusingpointerstoconstantdataorreferencestoconstantdata,toobtaintheperformancebenefitsofpass-by-reference.43SoftwareEngineeringObservation8.3Passlargeobjectsusingpointerstoconstantdata,orreferencestoconstantdata,toobtainthesecurityofpass-by-value.448.5UsingconstwithPointers(Cont.)Fourwaystopasspointertofunction(Cont.)ConstantpointertononconstantdataAlwayspointstothesamememorylocationCanonlyaccessotherelementsusingsubscriptnotationDatacanbemodifiedthroughthepointerDefaultforanarraynameCanbeusedbyafunctiontoreceiveanarrayargumentMustbeinitializedwhendeclared45Outlinefig08_13.cpp

(1of1)ptrisaconstantpointertoanintegerCanmodifyx(pointedtobyptr)sincexisnotconstantCannotmodifyptrtopointtoanewaddresssinceptrisconstantLine14generatesacompilererrorbyattemptingtoassignanewaddresstoaconstantpointer46CommonProgrammingError8.6Notinitializingapointerthatisdeclaredconstisacompilationerror.478.5UsingconstwithPointers(Cont.)Fourwaystopasspointertofunction(Cont.)ConstantpointertoconstantdataLeastamountofaccessAlwayspointstothesamememorylocationDatacannotbemodifiedusingthispointer48Outlinefig08_14.cpp

(1of2)ptrisaconstantpointertoaconstantintegerCannotmodifyx(pointedtobyptr)since*ptrisconstantCannotmodifyptrtopointtoanewaddresssinceptrisconstant49Outlinefig08_14.cpp

(2of2)Line18generatesacompilererrorbyattemptingtomodifyaconstantobjectLine19generatesacompilererrorbyattemptingtoassignanewaddresstoaconstantpointer508.6SelectionSortUsingPass-by-ReferenceImplementselectionSortusingpointersSelectionsortalgorithmSwapsmallestelementwiththefirstelementSwapsecond-smallestelementwiththesecondelementEtc.WantfunctionswaptoaccessarrayelementsIndividualarrayelements:scalarsPassedbyvaluebydefaultPassbyreferenceviapointersusingaddressoperator&51Outlinefig08_15.cpp

(1of3)52Outlinefig08_15.cpp

(2of3)Declarearrayasint*array(ratherthanintarray[])toindicatefunctionselectionSortreceivessingle-subscriptedarrayReceivesthesizeofthearrayasanargument;declaredconsttoensurethatsizeisnotmodified53Outlinefig08_15.cpp

(3of3)Argumentsarepassedbyreference,allowingthefunctiontoswapvaluesattheoriginalmemorylocations54SoftwareEngineeringObservation8.4Whenpassinganarraytoafunction,alsopassthesizeofthearray(ratherthanbuildingintothefunctionknowledgeofthearraysize).Thismakesthefunctionmorereusable.558.7sizeofOperatorssizeof

operatorReturnssizeofoperandinbytesForarrays,sizeofreturns(sizeof1element)*(numberofelements)Ifsizeof(int)returns4

then

intmyArray[10];

cout<<sizeof(myArray);willprint40CanbeusedwithVariablenamesTypenamesConstantvalues56CommonProgrammingError8.7Usingthesizeofoperatorinafunctiontofindthesizeinbytesofanarrayparameterresultsinthesizeinbytesofapointer,notthesizeinbytesofthearray.57Outlinefig08_16.cpp

(1of1)OperatorsizeofappliedtoanarrayreturnstotalnumberofbytesinthearrayFunctiongetSizereturnsthenumberofbytesusedtostorearrayaddressOperatorsizeofreturnsnumberofbytesofpointer588.7sizeofOperators(Cont.)sizeof

operator(Cont.)Isperformedatcompiler-timeFordoublerealArray[22];UsesizeofrealArray/sizeof(double)tocalculatethenumberofelementsinrealArrayParenthesesareonlyrequirediftheoperandisatypename59Outlinefig08_17.cpp(1of2)60Outlinefig08_17.cpp(2of2)OperatorsizeofcanbeusedonavariablenameOperatorsizeofcanbeusedonatypenameOperatorsizeofreturnsthetotalnumberofbytesinthearray61PortabilityTip8.2Thenumberofbytesusedtostoreaparticulardatatypemayvarybetweensystems.Whenwritingprogramsthatdependondatatypesizes,andthatwillrunonseveralcomputersystems,usesizeoftodeterminethenumberofbytesusedtostorethedatatypes.62CommonProgrammingError8.8Omittingtheparenthesesinasizeofoperationwhentheoperandisatypenameisacompilationerror.63PerformanceTip8.2Becausesizeofisacompile-timeunaryoperator,notanexecution-timeoperator,usingsizeofdoesnotnegativelyimpactexecutionperformance.64Error-PreventionTip8.3Toavoiderrorsassociatedwithomittingtheparenthesesaroundtheoperandofoperatorsizeof,manyprogrammersincludeparenthesesaroundeverysizeofoperand.658.8PointerExpressionsandPointerArithmeticPointerarithmeticIncrement/decrementpointer(++or--)Add/subtractanintegerto/fromapointer(+or+=,

-or-=)PointersmaybesubtractedfromeachotherPointerarithmeticismeaninglessunlessperformedonapointertoanarray668.8PointerExpressionsandPointerArithmetic(Cont.)5elementintarrayonamachineusing4byteintsvPtrpointstofirstelementv[

0

],atlocation3000vPtr=&v[0];vPtr+=2;setsvPtrto3008(3000+2*4)vPtrpointstov[2]SubtractingpointersReturnsnumberofelementsbetweentwoaddresses

vPtr2=v[2];

vPtr=v[0];

vPtr2-vPtris267PortabilityTip8.3Mostcomputerstodayhavetwo-byteorfour-byteintegers.Someofthenewermachinesuseeight-byteintegers.Becausetheresultsofpointerarithmeticdependonthesizeoftheobjectsapointerpointsto,pointerarithmeticismachinedependent.68Fig.8.18

|ArrayvandapointervariablevPtrthatpointstov.69Fig.8.19

|PointervPtrafterpointerarithmetic.70CommonProgrammingError8.9Usingpointerarithmeticonapointerthatdoesnotrefertoanarrayofvaluesisalogicerror.71CommonProgrammingError8.10Subtractingorcomparingtwopointersthatdonotrefertoelementsofthesamearrayisalogicerror.72CommonProgrammingError8.11Usingpointerarithmetictoincrementordecrementapointersuchthatthepointerreferstoanelementpasttheendofthearrayorbeforethebeginningofthearrayisnormallyalogicerror.738.8PointerExpressionsandPointerArithmetic(Cont.)PointerassignmentPointercanbeassignedtoanotherpointerifbothareofsametypeIfnotsametype,castoperatormustbeusedExceptionPointertovoid(typevoid

*)Genericpointer,representsanytypeNocastingneededtoconvertpointertovoid*Castingisneededtoconvertvoid*toanyothertypevoidpointerscannotbedereferenced74SoftwareEngineeringObservation8.5Nonconstantpointerargumentscanbepassedtoconstantpointerparameters.Thisishelpfulwhenthebodyofaprogramusesanonconstantpointertoaccessdata,butdoesnotwantthatdatatobemodifiedbyafunctioncalledinthebodyoftheprogram.75CommonProgrammingError8.12Assigningapointerofonetypetoapointerofanother(otherthanvoid

*)withoutcastingthefirstpointertothetypeofthesecondpointerisacompilationerror.76CommonProgrammingError8.13Alloperationsonavoid

*pointerarecompilationerrors,exceptcomparingvoid

*pointerswithotherpointers,castingvoid

*pointerstovalidpointertypesandassigningaddressestovoid*pointers.778.9RelationshipBetweenPointersandArraysArraysandpointersarecloselyrelatedArraynameislikeconstantpointerPointerscandoarraysubscriptingoperations788.9RelationshipBetweenPointersandArrays(Cont.)AccessingarrayelementswithpointersAssumedeclarations:

intb[5];

int*bPtr;

bPtr=b;Elementb[n]canbeaccessedby*(bPtr+n)Calledpointer/offsetnotationAddresses&b[3]issameasbPtr+3Arraynamecanbetreatedaspointerb[3]issameas

*(b+3)Pointerscanbesubscripted(pointer/subscriptnotation)bPtr[3]issameasb[3]79CommonProgrammingError8.14Althougharraynamesarepointerstothebeginningofthearrayandpointerscanbemodifiedinarithmeticexpressions,arraynamescannotbemodifiedinarithmeticexpressions,becausearraynamesareconstantpointers.80GoodProgrammingPractice8.2Forclarity,usearraynotationinsteadofpointernotationwhenmanipulatingarrays.81Outlinefig08_20.cpp

(1of3)UsingarraysubscriptnotationUsingarraynameandpointer/offsetnotation82Outlinefig08_20.cpp

(2of3)UsingpointersubscriptnotationUsingpointernameandpointer/offsetnotation83Outlinefig08_20.cpp

(3of3)84Outlinefig08_21.cpp

(1of2)85Outlinefig08_21.cpp

(2of2)Usearraysubscriptnotationtocopystringins2tocharacterarrays1Usepointernotationtocopystringins2tocharacterarrayins1Incrementbothpointerstopointtonextelementsincorrespondingarrays868.10ArraysofPointersArrayscancontainpointersCommonlyusedtostorearrayofstrings(stringarray)Arraydoesnotstorestrings,onlypointerstostringsExampleconstchar*suit[4]=

{"Hearts","Diamonds","Clubs","Spades"};Eachelementofsuitpointstoachar*(string)suitarrayhasfixedsize(4),butstringscanbeofanysizeCommonlyusedwithcommand-lineargumentstofunctionmain87Fig.8.22

|Graphicalrepresentationofthesuitarray.888.11CaseStudy:CardShufflingandDealingSimulationCardshufflingprogramUseanarrayofpointerstostrings,tostoresuitnamesUseadoublescriptedarray(suit-by-value)Place1-52intothearraytospecifytheorderinwhichthecardsaredealtIndefinitepostponement(starvation)AnalgorithmexecutingforanindefinitelylongperiodDuetorandomness89Fig.8.23

|Two-dimensionalarrayrepresentationofadeckofcards.90PerformanceTip8.3Sometimesalgorithmsthatemergeina“natural”waycancontainsubtleperformanceproblemssuchasindefinitepostponement.Seekalgorithmsthatavoidindefinitepostponement.918.11CaseStudy:CardShufflingandDealingSimulation(Cont.)Pseudocodeforshufflinganddealing

simulationForeachofthe52cards

Placecardnumberinrandomlyselectedunoccupiedslotofdeck

Foreachofthe52cards

FindcardnumberindeckarrayandprintfaceandsuitofcardChooseslotofdeckrandomly

Whilechosenslotofdeckhas

beenpreviouslychosen

Chooseslotofdeckrandomly

PlacecardnumberinchosenslotofdeckForeachslotofthedeckarray

Ifslotcontainscardnumber

Printthefaceandsuitofthe

cardSecondrefinementThirdrefinementFirstrefinementInitializethesuitarray

Initializethefacearray

Initializethedeckarray

Shufflethedeck

Deal52cards

92Outlinefig08_24.cpp

(1of1)93Outlinefig08_25.cpp

(1of1)94Outlinefig08_26.cpp

(1of4)95Outlinefig08_26.cpp

(2of4)Currentpositionisatrandomlyselectedrowandcolumn96Outlinefig08_26.cpp

(3of4)suitarraycontainspointerstochararraysfacearraycontainspointerstochararrays97Outlinefig08_26.cpp

(4of4)Causefacetobeoutputrightjustifiedinfieldof5charactersCausesuittobeoutputleftjustifiedinfieldof8characters98Outlinefig08_27.cpp

(1of2)99Outlinefig08_27.cpp

(2of2)1008.12FunctionPointersPointerstofunctionsContainaddressesoffunctionsSimilartohowarraynameisaddressoffirstelementFunctionnameisstartingaddressofcodethatdefinesfunctionFunctionpointerscanbePassedtofunctionsReturnedfromfunctionsStoredinarraysAssignedtootherfunctionpointers1018.12FunctionPointers(Cont.)CallingfunctionsusingpointersAssumefunctionheaderparameter:bool(*compare)(int,int)Executefunctionfrompointerwitheither(*compare)(int1,int2)Dereferencepointertofunction ORcompare(int1,int2)CouldbeconfusingUsermaythinkcompareisnameofactualfunctioninprogramFunctionpointerDeclareafunctionpointerUsethepointertopointafunctionCallthatfunctionbythepointer102103Outlinefig08_28.cpp

(1of4)Parameterispointertofunctionthatreceivestwointegerparametersandreturnsboolresult104Outlinefig08_28.cpp

(2of4)PasspointerstofunctionsascendinganddescendingasparameterstofunctionselectionSort105Outlinefig08_28.cpp

(3of4)compareisapointertoafunctionthatreceivestwointegerparametersandreturnsaboolresultParenthesesnecessarytoindicatepointertofunctionDereferencepointercomparetoexecutethefunction106Outlinefig08_28.cpp

(4of4)1078.12FunctionPointers(Cont.)ArraysofpointerstofunctionsMenu-drivensystemsPointerstoeachfunctionstoredinarrayofpointerstofunctionsAllfunctionsmusthavesamereturntypeandsameparametertypesMenuchoicedeterminessubscriptintoarrayoffunctionpointers108Outlinefig08_29.cpp

(1of3)Arrayinitializedwithnamesofthreefunctions109Outlinefig08_29.cpp

(2of3)Callchosenfunctionbydereferencingcorrespondingelementinarray110Outlinefig08_29.cpp

(3of3)1118.13IntroductiontoPointer-BasedStringProcessingStandardLibraryfunctionsforstringprocessingAppropriatefordevelopingtext-processingsoftware1128.13.1FundamentalsofCharactersandPointer-BasedStringsCharacterconstantIntegervaluerepresentedascharacterinsinglequotesExample'z'isintegervalueofz122inASCII'\n'isintegervalueofnewline10inASCII1138.13.1FundamentalsofCharactersandPointer-BasedStrings(Cont.)StringSeriesofcharacterstreatedassingleunitCanincludeletters,digits,specialcharacters+,-,*,...Stringliteral(stringconstants)Enclosedindoublequotes,forexample:"IlikeC++“HavestaticstorageclassArrayofcharacters,endswithnullcharacter'\0'StringisconstantpointerPointertostring’sfirstcharacterLikearrays1148.13.1FundamentalsofCharactersandPointer-BasedStrings(Cont.)StringassignmentCharacterarraycharcolor[]="blue";

Creates5elementchararraycolor

Lastelementis'\0'Variableoftypechar*char*colorPtr="blue";CreatespointercolorPtrtoletterbinstring"blue""blue"somewhereinmemoryAlternativeforcharacterarraycharcolor[]={'b','l','u','e','\0'};115CommonProgrammingError8.15Notallocatingsufficientspaceinacharacterarraytostorethenullcharacterthatterminatesastringisanerror.116CommonProgrammingError8.16CreatingorusingaC-stylestringthatdoesnotcontainaterminatingnullcharactercanleadtologicerrors.117Error-PreventionTip8.4Whenstoringastringofcharactersinacharacterarray,besurethatthearrayislargeenoughtoholdthelargeststringthatwillbestored.C++allowsstringsofanylengthtobestored.Ifastringislongerthanthecharacterarrayinwhichitistobestored,charactersbeyondtheendofthearraywilloverwritedatainmemoryfollowingthearray,leadingtologicerrors.1188.13.1FundamentalsofCharactersandPointer-BasedStrings(Cont.)ReadingstringsAssigninputtocharacterarrayword[20]cin>>word;

ReadscharactersuntilwhitespaceorEOFStringcouldexceedarraysizecin>>setw(20)>>word;Readsonlyupto19characters(spacereservedfor'\0')1198.13.1FundamentalsofCharactersandPointer-BasedStrings(Cont.)cin.getlineReadlineoftextcin.getline(array,size,delimiter);CopiesinputintospecifiedarrayuntileitherOnelessthansizeisreacheddelimitercharacterisinputExamplecharsentence[80];

cin.getline(sentence,80,'\n');120CommonProgrammingError8.17Processingasinglecharacterasachar*stringcanleadtoafatalruntimeerror.Achar

*stringisapointer—probablyarespectablylargeinteger.However,acharacterisasmallinteger(ASCIIvaluesrange0–255).Onmanysystems,dereferencingacharvaluecausesanerror,becauselowmemoryaddressesarereservedforspecialpurposessuchasoperatingsysteminterrupthandlers—so“memoryaccessviolations”occur.121CommonProgrammingError8.18Passingastringasanargumenttoafunctionwhenacharacterisexpectedisacompilationerror.1228.13.2StringManipulationFunctionsoftheString-HandlingLibraryStringhandlinglibrary<cstring>providesfunctionstoManipulatestringdataComparestringsSearchstringsforcharactersandotherstringsTokenizestrings(separatestringsintologicalpieces)Datatypesize_tDefinedtobeanunsignedintegraltypeSuchasunsignedintorunsignedlongInheaderfile<cstring>123Fig.8.30

|String-manipulationfunctionsofthestring-handlinglibrary.(Part1of2)124Fig.8.30

溫馨提示

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

評論

0/150

提交評論