Tải bản đầy đủ - 0 (trang)
Chapter 22. Bits, Characters, C-Strings and structs

Chapter 22. Bits, Characters, C-Strings and structs

Tải bản đầy đủ - 0trang

Chapter22.Bits,Characters,C-Strings

andstructs

Thesameoldcharitablelie

Repeatedastheyearsscootby

Perpetuallymakesahit

"Youreallyhaven'tchangedabit!"

MargaretFishback

ThechiefdefectofHenryKing

Waschewinglittlebitsofstring.

HilaireBelloc

Vigorouswritingisconcise.

Asentenceshouldcontainnounnecessarywords,a

paragraphnounnecessarysentences.

WilliamStrunk,Jr.

OBJECTIVES

Inthischapteryouwilllearn:

Tocreateandusestructs.

Topassstructstofunctionsbyvalueandbyreference.



Tousetypedeftocreatealiasesforpreviouslydefineddata

typesandstructs.

Tomanipulatedatawiththebitwiseoperatorsandtocreate

bitfieldsforstoringdatacompactly.

Tousethefunctionsofthecharacter-handlinglibrary

.

Tousethestring-conversionfunctionsofthegeneralutilitieslibrary.

Tousethestring-processingfunctionsofthestring-handling

library.



[Page1058]

Outline

22.1Introduction

22.2StructureDefinitions

22.3InitializingStructures

22.4UsingStructureswithFunctions

22.5typedef

22.6Example:High-PerformanceCardShufflingandDealing

Simulation

22.7BitwiseOperators

22.8BitFields

22.9Character-HandlingLibrary



22.10Pointer-BasedString-ConversionFunctions

22.11SearchFunctionsofthePointer-BasedString-Handling

Library

22.12MemoryFunctionsofthePointer-BasedString-Handling

Library

22.13Wrap-Up

Summary

Terminology

Self-ReviewExercises

AnswerstoSelf-ReviewExercises

Exercises



[Page1058(continued)]



22.1.Introduction

Inthischapter,wediscussstructuresandthemanipulationof

bits,charactersandC-stylestrings.Manyofthetechniqueswe

presenthereareincludedforthebenefitoftheC++

programmerwhowillworkwithC,andearlyC++,legacycode.

ThedesignersofC++evolvedstructuresintothenotionofa

class.Likeaclass,C++structurescancontainaccessspecfiers,

memberfunctions,constructorsanddestructors.Infact,the

onlydifferencebetweenstructuresandclassesinC++isthat

structuremembersdefaulttopublicaccessandclassmembers

defaulttoprivateaccesswhennoaccessspecifiersareused.

Classeshavebeencoveredthoroughlyinthebook,sothereis

reallynoneedforustodiscussstructuresindetail.Our

presentationofstructuresinthischapterfocusesontheirusein

C,wherestructurescontainonlypublicdatamembers.Thisuse

ofstructuresistypicalofthelegacyCcodeandearlyC++code

you'llseeinindustry.

Wediscusshowtodeclarestructures,initializestructuresand

passstructurestofunctions.Then,wepresentahighperformancecardshufflinganddealingsimulationinwhichwe

usestructureobjectsandC-stylestringstorepresentthecards.

Wediscussthebitwiseoperatorsthatallowprogrammersto

accessandmanipulatetheindividualbitsinbytesofdata.We

alsopresentbitfieldsspecialstructuresthatcanbeusedto

specifytheexactnumberofbitsavariableoccupiesinmemory.

ThesebitmanipulationtechniquesarecommoninCandC++

programsthatinteractdirectlywithhardwaredevicesthathave

limitedmemory.Thechapterfinisheswithexamplesofmany

characterandC-stylestringmanipulationfunctionssomeof

whicharedesignedtoprocessblocksofmemoryasarraysof

bytes.



[Page1058(continued)]



22.2.StructureDefinitions

Structuresareaggregatedatatypesthatis,theycanbebuilt

usingelementsofseveraltypesincludingotherstructs.Consider

thefollowingstructuredefinition:



[Page1059]

structCard

{

char*face;

char*suit;

};//endstructCard



KeywordstructintroducesthedefinitionforstructureCard.The

identifierCardisthestructurenameandisusedinC++to

declarevariablesofthestructuretype(inC,thetypenameof

theprecedingstructureisstructCard).Inthisexample,the

structuretypeisCard.Data(andpossiblyfunctionsjustaswith

classes)declaredwithinthebracesofthestructuredefinition

arethestructure'smembers.Membersofthesamestructure

musthaveuniquenames,buttwodifferentstructuresmay

containmembersofthesamenamewithoutconflict.Each

structuredefinitionmustendwithasemicolon.



CommonProgrammingError22.1

Forgettingthesemicolonthatterminatesastructure

definitionisasyntaxerror.



ThedefinitionofCardcontainstwomembersoftypechar*face

andsuit.Structurememberscanbevariablesofthe

fundamentaldatatypes(e.g.,int,double,etc.)oraggregates,

suchasarrays,otherstructuresandorclasses.Datamembers

inasinglestructuredefinitioncanbeofmanydatatypes.For

example,anEmployeestructuremightcontaincharacter-string

membersforthefirstandlastnames,anintmemberforthe

employee'sage,acharmembercontaining'M'or'F'forthe

employee'sgender,adoublememberfortheemployee'shourly

salaryandsoon.

Astructurecannotcontainaninstanceofitself.Forexample,a

structurevariableCardcannotbedeclaredinthedefinitionfor

structureCard.ApointertoaCardstructure,however,canbe

included.Astructurecontainingamemberthatisapointerto

thesamestructuretypeisreferredtoasaself-referential

structure.Weusedasimilarconstructself-referentialclassesin

Chapter21,DataStructures,tobuildvariouskindsoflinked

datastructures.

TheCardstructuredefinitiondoesnotreserveanyspacein

memory;rather,itcreatesanewdatatypethatisusedto

declarestructurevariables.Structurevariablesaredeclaredlike

variablesofothertypes.Thefollowingdeclarations

CardoneCard;

Carddeck[52];

Card*cardPtr;



declareoneCardtobeastructurevariableoftypeCard,decktobe

anarraywith52elementsoftypeCardandcardPtrtobea

pointertoaCardstructure.Variablesofagivenstructuretype

canalsobedeclaredbyplacingacomma-separatedlistofthe



variablenamesbetweentheclosingbraceofthestructure

definitionandthesemicolonthatendsthestructuredefinition.

Forexample,theprecedingdeclarationscouldhavebeen

incorporatedintotheCardstructuredefinitionasfollows:

structCard

{

char*face;

char*suit;

}oneCard,deck[52],*cardPtr;



[Page1060]

Thestructurenameisoptional.Ifastructuredefinitiondoesnot

containastructurename,variablesofthestructuretypemay

bedeclaredonlybetweentheclosingrightbraceofthe

structuredefinitionandthesemicolonthatterminatesthe

structuredefinition.



SoftwareEngineeringObservation22.1

Provideastructurenamewhencreatingastructuretype.

Thestructurenameisrequiredfordeclaringnew

variablesofthestructuretypelaterintheprogram,

declaringparametersofthestructuretypeand,ifthe

structureisbeingusedlikeaC++class,specifyingthe

nameoftheconstructoranddestructor.



Theonlyvalidbuilt-inoperationsthatmaybeperformedon

structureobjectsareassigningastructureobjecttoastructure

objectofthesametype,takingtheaddress(&)ofastructure



object,accessingthemembersofastructureobject(inthe

samemannerasmembersofaclassareaccessed)andusing

thesizeofoperatortodeterminethesizeofastructure.Aswith

classes,mostoperatorscanbeoverloadedtoworkwithobjects

ofastructuretype.

Structuremembersarenotnecessarilystoredinconsecutive

bytesofmemory.Sometimesthereare"holes"inastructure,

becausesomecomputersstorespecificdatatypesonlyon

certainmemoryboundaries,suchashalf-word,wordordoublewordboundaries.Awordisastandardmemoryunitusedto

storedatainacomputerusuallytwobytesorfourbytesand

typicallyfourbytesontoday'spopular32-bitsystems.Consider

thefollowingstructuredefinitioninwhichstructureobjects

sample1andsample2oftypeExamplearedeclared:

structExample

{

charc;

inti;

}sample1,sample2;



Acomputerwithtwo-bytewordsmightrequirethateachofthe

membersofExamplebealignedonawordboundary(i.e.,atthe

beginningofawordthisismachinedependent).Figure22.1

showsasamplestoragealignmentforanobjectoftypeExample

thathasbeenassignedthecharacter'a'andtheinteger97(the

bitrepresentationsofthevaluesareshown).Ifthemembers

arestoredbeginningatwordboundaries,thereisaone-byte

hole(byte1inthefigure)inthestorageforobjectsoftype

Example.Thevalueinthe1-byteholeisundefined.Ifthe

membervaluesofsample1andsample2areinfactequal,the

structureobjectsarenotnecessarilyequal,becausethe

undefined1-byteholesarenotlikelytocontainidenticalvalues.



Figure22.1.Possiblestoragealignmentfora

variableoftypeExample,showinganundefined

areainmemory.



[Viewfullsizeimage]



CommonProgrammingError22.2

Comparingstructuresisacompilationerror.



[Page1061]

PortabilityTip22.1

Becausethesizeofdataitemsofaparticulartypeis

machinedependent,andbecausestoragealignment

considerationsaremachinedependent,sotooisthe

representationofastructure.



[Page1061(continued)]



22.3.InitializingStructures

Structurescanbeinitializedusinginitializerlists,asisdone

witharrays.Forexample,thedeclaration

CardoneCard={"Three","Hearts"};



createsCardvariableoneCardandinitializesmemberfaceto"Three"

andmembersuitto"Hearts".Iftherearefewerinitializersinthe

listthanmembersinthestructure,theremainingmembersare

initializedtotheirdefaultvalues.Structurevariablesdeclared

outsideafunctiondefinition(i.e.,externally)areinitializedto

theirdefaultvaluesiftheyarenotexplicitlyinitializedinthe

externaldeclaration.Structurevariablesmayalsobesetin

assignmentexpressionsbyassigningastructurevariableofthe

sametypeorbyassigningvaluestotheindividualdata

membersofthestructure.



[Page1061(continued)]



22.4.UsingStructureswithFunctions

Therearetwowaystopasstheinformationinstructuresto

functions.Youcaneitherpasstheentirestructureorpassthe

individualmembersofastructure.Bydefault,structuresare

passedbyvalue.Structuresandtheirmemberscanalsobe

passedbyreferencebypassingeitherreferencesorpointers.

Topassastructurebyreference,passtheaddressofthe

structureobjectorareferencetothestructureobject.Arraysof

structureslikeallotherarraysarepassedbyreference.

InChapter7,westatedthatanarraycouldbepassedbyvalue

byusingastructure.Topassanarraybyvalue,createa

structure(oraclass)withthearrayasamember,thenpassan

objectofthatstructure(orclass)typetoafunctionbyvalue.

Becausestructureobjectsarepassedbyvalue,thearray

member,too,ispassedbyvalue.



PerformanceTip22.1

Passingstructures(andespeciallylargestructures)by

referenceismoreefficientthanpassingthembyvalue

(whichrequirestheentirestructuretobecopied).



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 22. Bits, Characters, C-Strings and structs

Tải bản đầy đủ ngay(0 tr)

×