Sunteți pe pagina 1din 3

TheCBook&#8212Arrays

5.2.Arrays
Likeotherlanguages,Cusesarraysasawayofdescribingacollectionofvariableswithidentical
properties.Thegrouphasasinglenameforallofthemembers,withtheindividualmembersbeing
selectedbyanindex.Here'sanarraybeingdeclared:
double ar[100];
Thenameofthearrayisaranditsmembersareaccessedasar[0]throughtoar[99]inclusive,
asFigure5.1shows.

Figure5.1.100elementarray
Eachofthehundredmembersisaseparatevariablewhosetypeisdouble.Withoutexception,all
arraysinCarenumberedfrom0uptoonelessthantheboundgiveninthedeclaration.Thisisa
primecauseofsurprisetobeginnerswatchoutforit.Forsimpleexamplesoftheuseofarrays,look
backatearlierchapterswhereseveralproblemsaresolvedwiththeirhelp.
Oneimportantpointaboutarraydeclarationsisthattheydon'tpermittheuseofvaryingsubscripts.
Thenumbersgivenmustbeconstantexpressionswhichcanbeevaluatedatcompiletime,notrun
time.Forexample,thisfunctionincorrectlytriestouseitsargumentinthesizeofanarraydeclaration:
f(int x){
char var_sized_array[x];

/* FORBIDDEN */

}
It'sforbiddenbecausethevalueofxisunknownwhentheprogramiscompiledit'saruntime,nota
compiletime,value.
Totellthetruth,itwouldbeeasytosupportarrayswhosefirstdimensionisvariable,butneitherOldC
northeStandardpermitsit,althoughwedoknowofoneVeryOldCcompilerthatusedtodoit.

5.2.1.Multidimensionalarrays
Multidimensionalarrayscanbedeclaredlikethis:

int three_dee[5][4][2];
int t_d[2][3]
Theuseofthebracketsgivesacluetowhatisgoingon.Ifyourefertotheprecedencetablegivenin
Section2.8.3(Table2.9),you'llseethat[]associateslefttorightandthat,asaresult,thefirst
declarationgivesusafiveelementarraycalledthree_dee.Themembersofthatarrayareeacha
fourelementarraywhosemembersareanarrayoftwoints.Wehavedeclaredarraysofarrays,as
Figure5.2showsfortwodimensions.

Figure5.2.Twodimensionalarray,showinglayout
Inthediagram,youwillnoticethatt_d[0]isoneelement,immediatelyfollowedbyt_d[1](thereis
nobreak).Itsohappensthatbothofthoseelementsarethemselvesarraysofthreeintegers.
BecauseofC'sstoragelayoutrules,t_d[1][0]isimmediatelyaftert_d[0][2].Itwouldbepossible
(butverypoorpractice)toaccesst_d[1][0]bymakinguseofthelackofarrayboundcheckingin
C,andtousetheexpressiont_d[0][3].Thatisnotrecommendedapartfromanythingelse,ifthe
declarationoft_deverchanges,thentheresultswillbelikelytosurpriseyou.
That'sallverywell,butdoesitreallymatterinpractice?Notmuchit'struebutitisinterestingtonote
thatintermsofactualmachinestoragelayouttherightmostsubscriptvariesfastest.Thishasan
impactwhenarraysareaccessedviapointers.Otherwise,theycanbeusedjustaswouldbe
expectedexpressionslikethesearequiteinorder:
three_dee[1][3][1] = 0;
three_dee[4][3][1] += 2;
Thesecondofthoseisinterestingfortworeasons.First,itaccessestheverylastmemberofthe
entirearrayalthoughthesubscriptsweredeclaredtobe[5][4][2],thehighestusablesubscriptis
alwaysonelessthantheoneusedinthedeclaration.Second,itshowswherethecombined
assignmentoperatorsarearealblessing.FortheexperiencedCprogrammeritismucheasiertotell
thatonlyonearraymemberisbeingaccessed,andthatitisbeingincrementedbytwo.Other
languageswouldhavetoexpressitlikethis:
three_dee[4][3][1] = three_dee[4][3][1] + 2;
Ittakesaconsciousefforttocheckthatthesamearraymemberisbeingreferencedonbothsidesof
theassignment.Itmakesthingeasierforthecompilertoo:thereisonlyonearrayindexingcalculation
todo,andthisislikelytoresultinshorter,fastercode.(Ofcourseaclevercompilerwouldnoticethat
theleftandrighthandsideslookalikeandwouldbeabletogenerateequallyefficientcodebutnot

allcompilersarecleverandtherearelotsofspecialcaseswhereevenclevercompilersareunableto
makeuseoftheinformation.)
ItmaybeofinteresttoknowthatalthoughCofferssupportformultidimensionalarrays,theyaren't
particularlycommontoseeinpractice.Onedimensionalarraysarepresentinmostprograms,iffor
nootherreasonthanthat'swhatstringsare.Twodimensionalarraysareseenoccasionally,and
arraysofhigherorderthanthataremostuncommon.Oneofthereasonsisthatthearrayisarather
inflexibledatastructure,andtheeaseofbuildingandmanipulatingothertypesofdatastructuresinC
meansthattheytendtoreplacearraysinthemoreadvancedprograms.Wewillseemoreofthis
whenwelookatpointers.

S-ar putea să vă placă și