Tải bản đầy đủ - 0 (trang)
Chapter 14. Structures and Other Data Forms

Chapter 14. Structures and Other Data Forms

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

useone.



SampleProblem:CreatinganInventoryof

Books

GwenGlennwantstoprintaninventoryofherbooks.She

wouldliketoprintavarietyofinformationforeachbook:title,

author,publisher,copyrightdate,thenumberofpages,the

numberofcopies,andthedollarvalue.Someoftheseitems,

suchasthetitles,canbestoredinanarrayofstrings.Other

itemsrequireanarrayofintsoranarrayoffloats.With

sevendifferentarrays,keepingtrackofeverythingcanget

complicated,especiallyifGwenwantstogenerateseveral

completelistsonesortedbytitle,onesortedbyauthor,one

sortedbyvalue,andsoon.Abettersolutionistouseonearray,

inwhicheachmembercontainsalltheinformationaboutone

book.

Gwenneedsadataform,then,thatcancontainbothstrings

andnumbersandsomehowkeeptheinformationseparate.The

Cstructuremeetsthisneed.Toseehowastructureissetup

andhowitworks,we'llstartwithalimitedexample.Tosimplify

theproblem,wewillimposetworestrictions.First,we'llinclude

onlytitle,author,andcurrentmarketvalue.Second,we'lllimit

theinventorytoonebook.Don'tworryaboutthislimitation,

however,becausewe'llextendtheprogramsoon.

LookattheprograminListing14.1anditsoutput.Thenread

theexplanationofthemainpoints.



Listing14.1.Thebook.cProgram



/*book.c--one-bookinventory*/

#include



#defineMAXTITL41/*maximumlengthoftitle+1



#defineMAXAUTL31/*maximumlengthofauthor'sname+1



structbook{/*structuretemplate:tagisbook

chartitle[MAXTITL];

charauthor[MAXAUTL];

floatvalue;



};/*endofstructuretemplate



intmain(void)

{



structbooklibrary;/*declarelibraryasabookvariable



printf("Pleaseenterthebooktitle.\n");



gets(library.title);/*accesstothetitleportion

printf("Nowentertheauthor.\n");

gets(library.author);

printf("Nowenterthevalue.\n");



scanf("%f",&library.value);

printf("%sby%s:$%.2f\n",library.title,

library.author,library.value);

printf("%s:\"%s\"($%.2f)\n",library.author,

library.title,library.value);

printf("Done.\n");



return0;

}



Hereisasamplerun:



Pleaseenterthebooktitle.

ChickenoftheAlps

Nowentertheauthor.

BismoLapoult



Nowenterthevalue.

14.95

ChickenoftheAlpsbyBismoLapoult:$14.95

BismoLapoult:"ChickenoftheAlps"($14.95)



ThestructurecreatedinListing14.1hasthreeparts(called

membersorfields)onetostorethetitle,onetostorethe

author,andonetostorethevalue.Thesearethethreemain

skillsyoumustacquire:

Settingupaformatorlayoutforastructure

Declaringavariabletofitthatlayout

Gainingaccesstotheindividualcomponentsofastructure

variable



SettingUptheStructureDeclaration

Astructuredeclarationisthemasterplanthatdescribeshowa

structureisputtogether.Thedeclarationlookslikethis:



structbook{

chartitle[MAXTITL];

charauthor[MAXAUTL];

floatvalue;

};



Thisdeclarationdescribesastructuremadeupoftwocharacter

arraysandonefloatvariable.Itdoesnotcreateanactualdata

object,butitdescribeswhatconstitutessuchanobject.

(Occasionally,we'llrefertoastructuredeclarationasa

templatebecauseitoutlineshowdatawillbestored.Ifyou've

heardoftemplatesinC++,that'sadifferent,moreambitious

useoftheword.)Let'slookatthedetails.Firstcomesthe

keywordstruct.Itidentifieswhatcomesnextasastructure.

Nextcomesanoptionaltagthewordbookthatisashorthand

labelyoucanusetorefertothisstructure.Therefore,laterwe



havethisdeclaration:



structbooklibrary;



Itdeclareslibrarytobeastructurevariableusingthebook

structuredesign.

Nextinthestructuredeclaration,thelistofstructuremembers

areenclosedinapairofbraces.Eachmemberisdescribedby

itsowndeclaration,completewithaterminatingsemicolon.For

example,thetitleportionisachararraywithMAXTITL

elements.AmembercanbeanyCdatatypeandthatincludes

otherstructures!

Asemicolonaftertheclosingbraceendsthedefinitionofthe

structuredesign.Youcanplacethisdeclarationoutsideany

function(externally),aswehavedone,orinsideafunction

definition.Ifthedeclarationisplacedinsideafunction,itstag

canbeusedonlyinsidethatfunction.Ifthedeclarationis

external,itisavailabletoallthefunctionsfollowingthe

declarationinthefile.Forexample,inasecondfunction,you

coulddefine



structbookdickens;



andthatfunctionwouldhaveavariable,dickens,thatfollows

theformofthebookdesign.

Thetagnameisoptional,butyoumustuseonewhenyouset

upstructuresaswedid,withthestructuredesigndefinedone

placeandtheactualvariablesdefinedelsewhere.Wewillreturn

tothispointsoon,afterwelookatdefiningstructurevariables.



DefiningaStructureVariable

Thewordstructureisusedintwosenses.Oneisthesense

"structureplan,"whichiswhatwejustdiscussed.Thestructure

plantellsthecompilerhowtorepresentthedata,butitdoesn't

makethecomputerallocatespaceforthedata.Thenextstepis

tocreatea"structurevariable,"thesecondsenseoftheword.

Thelineintheprogramthatcausesastructurevariabletobe

createdisthis:



structbooklibrary;



Seeingthisinstruction,thecompilercreatesthevariable

library.Usingthebooktemplate,thecompilerallotsspacefor

achararrayofMAXTITLelements,forachararrayofMAXAUTL

elements,andforafloatvariable.Thisstorageislumped

togetherunderthesinglenamelibrary(seeFigure14.1).

(Thenextsectionexplainshowtounlumpitasneeded.)



Figure14.1.Memoryallocationforastructure.



Indeclaringastructurevariable,structbookplaysthesame

rolethatintorfloatdoesinsimplerdeclarations.For

example,youcoulddeclaretwovariablesofthestructbook

typeorevenapointertothatkindofstructure:



structbookdoyle,panshin,*ptbook;



Thestructurevariablesdoyleandpanshinwouldeachhavethe

partstitle,author,andvalue.Thepointerptbookcouldpoint

todoyle,panshin,oranyotherbookstructure.Inessence,the

bookstructuredeclarationcreatesanewtypecalledstruct

book.

Asfarasthecomputerisconcerned,thedeclaration



structbooklibrary;



isshortfor



structbook{

chartitle[MAXTITL];

charauthor[AXAUTL];

floatvalue;

}library;/*followdeclarationwithvariablename*/



Inotherwords,theprocessofdeclaringastructureandthe

processofdefiningastructurevariablecanbecombinedinto

onestep.Combiningthedeclarationandthevariable

definitions,asshownhere,istheonecircumstanceinwhicha



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

Chapter 14. Structures and Other Data Forms

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

×