Académique Documents
Professionnel Documents
Culture Documents
Search: Go
Notloggedin
C++
Information
Tutorials
Reference
Articles
Forum
Tutorials Arrays
C++Language Anarrayisaseriesofelementsofthesametypeplacedincontiguousmemorylocationsthatcanbeindividually
AsciiCodes referencedbyaddinganindextoauniqueidentifier.
BooleanOperations
NumericalBases Thatmeansthat,forexample,fivevaluesoftypeintcanbedeclaredasanarraywithouthavingtodeclare5different
variables(eachwithitsownidentifier).Instead,usinganarray,thefiveintvaluesarestoredincontiguousmemory
C++Language locations,andallfivecanbeaccessedusingthesameidentifier,withtheproperindex.
Introduction:
Compilers Forexample,anarraycontaining5integervaluesoftypeintcalledfoocouldberepresentedas:
BasicsofC++:
Structureofaprogram
Variablesandtypes whereeachblankpanelrepresentsanelementofthearray.Inthiscase,thesearevaluesoftypeint.Theseelements
Constants arenumberedfrom0to4,being0thefirstand4thelastInC++,thefirstelementinanarrayisalwaysnumbered
Operators withazero(notaone),nomatteritslength.
BasicInput/Output
Programstructure: Likearegularvariable,anarraymustbedeclaredbeforeitisused.AtypicaldeclarationforanarrayinC++is:
Statementsandflowcontrol
Functions typename[elements];
Overloadsandtemplates
Namevisibility wheretypeisavalidtype(suchasint,float...),nameisavalididentifierandtheelementsfield(whichisalwaysenclosed
Compounddatatypes: insquarebrackets[]),specifiesthelengthofthearrayintermsofthenumberofelements.
Arrays
Therefore,thefooarray,withfiveelementsoftypeint,canbedeclaredas:
Charactersequences
Pointers
intfoo[5];
Dynamicmemory
Datastructures
Otherdatatypes
Classes: NOTE:Theelementsfieldwithinsquarebrackets[],representingthenumberofelementsinthearray,mustbea
Classes(I) constantexpression,sincearraysareblocksofstaticmemorywhosesizemustbedeterminedatcompiletime,beforethe
programruns.
Classes(II)
Specialmembers
Friendshipandinheritance
Initializingarrays
Polymorphism
Otherlanguagefeatures: Bydefault,regulararraysoflocalscope(forexample,thosedeclaredwithinafunction)areleftuninitialized.Thismeans
Typeconversions thatnoneofitselementsaresettoanyparticularvaluetheircontentsareundeterminedatthepointthearrayis
Exceptions declared.
Preprocessordirectives
Buttheelementsinanarraycanbeexplicitlyinitializedtospecificvalueswhenitisdeclared,byenclosingthoseinitial
Standardlibrary:
valuesinbraces{}.Forexample:
Input/outputwithfiles
intfoo[5]={16,2,77,40,12071};
Thisstatementdeclaresanarraythatcanberepresentedlikethis:
Thenumberofvaluesbetweenbraces{}shallnotbegreaterthanthenumberofelementsinthearray.Forexample,in
theexampleabove,foowasdeclaredhaving5elements(asspecifiedbythenumberenclosedinsquarebrackets,[]),
andthebraces{}containedexactly5values,oneforeachelement.Ifdeclaredwithless,theremainingelementsareset
totheirdefaultvalues(whichforfundamentaltypes,meanstheyarefilledwithzeroes).Forexample:
intbar[5]={10,20,30};
Willcreateanarraylikethis:
Theinitializercanevenhavenovalues,justthebraces:
intbaz[5]={};
Thiscreatesanarrayoffiveintvalues,eachinitializedwithavalueofzero:
Whenaninitializationofvaluesisprovidedforanarray,C++allowsthepossibilityofleavingthesquarebracketsempty
[].Inthiscase,thecompilerwillassumeautomaticallyasizeforthearraythatmatchesthenumberofvaluesincluded
betweenthebraces{}:
intfoo[]={16,2,77,40,12071};
Afterthisdeclaration,arrayfoowouldbe5intlong,sincewehaveprovided5initializationvalues.
Finally,theevolutionofC++hasledtotheadoptionofuniversalinitializationalsoforarrays.Therefore,thereisnolonger
needfortheequalsignbetweenthedeclarationandtheinitializer.Boththesestatementsareequivalent:
1 intfoo[]={10,20,30};
2 intfoo[]{10,20,30};
http://www.cplusplus.com/doc/tutorial/arrays/ 1/4
8/14/2015 ArraysC++Tutorials
Staticarrays,andthosedeclareddirectlyinanamespace(outsideanyfunction),arealwaysinitialized.Ifnoexplicit
initializerisspecified,alltheelementsaredefaultinitialized(withzeroes,forfundamentaltypes).
Accessingthevaluesofanarray
Thevaluesofanyoftheelementsinanarraycanbeaccessedjustlikethevalueofaregularvariableofthesametype.
Thesyntaxis:
name[index]
Followingthepreviousexamplesinwhichfoohad5elementsandeachofthoseelementswasoftypeint,thename
whichcanbeusedtorefertoeachelementisthefollowing:
Forexample,thefollowingstatementstoresthevalue75inthethirdelementoffoo:
foo[2]=75;
and,forexample,thefollowingcopiesthevalueofthethirdelementoffootoavariablecalledx:
x=foo[2];
Therefore,theexpressionfoo[2]isitselfavariableoftypeint.
Noticethatthethirdelementoffooisspecifiedfoo[2],sincethefirstoneisfoo[0],thesecondoneisfoo[1],and
therefore,thethirdoneisfoo[2].Bythissamereason,itslastelementisfoo[4].Therefore,ifwewritefoo[5],wewould
beaccessingthesixthelementoffoo,andthereforeactuallyexceedingthesizeofthearray.
InC++,itissyntacticallycorrecttoexceedthevalidrangeofindicesforanarray.Thiscancreateproblems,since
accessingoutofrangeelementsdonotcauseerrorsoncompilation,butcancauseerrorsonruntime.Thereasonforthis
beingallowedwillbeseeninalaterchapterwhenpointersareintroduced.
Atthispoint,itisimportanttobeabletoclearlydistinguishbetweenthetwousesthatbrackets[]haverelatedto
arrays.Theyperformtwodifferenttasks:oneistospecifythesizeofarrayswhentheyaredeclaredandthesecondone
istospecifyindicesforconcretearrayelementswhentheyareaccessed.Donotconfusethesetwopossibleusesof
brackets[]witharrays.
1 intfoo[5];//declarationofanewarray
2 foo[2]=75;//accesstoanelementofthearray.
Themaindifferenceisthatthedeclarationisprecededbythetypeoftheelements,whiletheaccessisnot.
Someothervalidoperationswitharrays:
1 foo[0]=a;
2 foo[a]=75;
3 b=foo[a+2];
4 foo[foo[a]]=foo[2]+5;
Forexample:
1 //arraysexample 12206
2 #include<iostream> Edit
3 usingnamespacestd;
4
5 intfoo[]={16,2,77,40,12071};
6 intn,result=0;
7
8 intmain()
9 {
10 for(n=0;n<5;++n)
11 {
12 result+=foo[n];
13 }
14 cout<<result;
15 return0;
16 }
Multidimensionalarrays
Multidimensionalarrayscanbedescribedas"arraysofarrays".Forexample,abidimensionalarraycanbeimaginedasa
twodimensionaltablemadeofelements,allofthemofasameuniformdatatype.
jimmyrepresentsabidimensionalarrayof3per5elementsoftypeint.TheC++syntaxforthisis:
intjimmy[3][5];
and,forexample,thewaytoreferencethesecondelementverticallyandfourthhorizontallyinanexpressionwouldbe:
jimmy[1][3]
http://www.cplusplus.com/doc/tutorial/arrays/ 2/4
8/14/2015 ArraysC++Tutorials
(rememberthatarrayindicesalwaysbeginwithzero).
Multidimensionalarraysarenotlimitedtotwoindices(i.e.,twodimensions).Theycancontainasmanyindicesasneeded.
Althoughbecareful:theamountofmemoryneededforanarrayincreasesexponentiallywitheachdimension.For
example:
charcentury[100][365][24][60][60];
declaresanarraywithanelementoftypecharforeachsecondinacentury.Thisamountstomorethan3billionchar!
Sothisdeclarationwouldconsumemorethan3gigabytesofmemory!
Attheend,multidimensionalarraysarejustanabstractionforprogrammers,sincethesameresultscanbeachievedwith
asimplearray,bymultiplyingitsindices:
1 intjimmy[3][5];//isequivalentto
2 intjimmy[15];//(3*5=15)
Withtheonlydifferencethatwithmultidimensionalarrays,thecompilerautomaticallyremembersthedepthofeach
imaginarydimension.Thefollowingtwopiecesofcodeproducetheexactsameresult,butoneusesabidimensionalarray
whiletheotherusesasimplearray:
multidimensionalarray pseudomultidimensionalarray
#defineWIDTH5 #defineWIDTH5
#defineHEIGHT3 #defineHEIGHT3
intjimmy[HEIGHT][WIDTH]; intjimmy[HEIGHT*WIDTH];
intn,m; intn,m;
intmain() intmain()
{ {
for(n=0;n<HEIGHT;n++) for(n=0;n<HEIGHT;n++)
for(m=0;m<WIDTH;m++) for(m=0;m<WIDTH;m++)
{ {
jimmy[n][m]=(n+1)*(m+1); jimmy[n*WIDTH+m]=(n+1)*(m+1);
} }
} }
Noneofthetwocodesnippetsaboveproduceanyoutputonthescreen,butbothassignvaluestothememoryblock
calledjimmyinthefollowingway:
Notethatthecodeusesdefinedconstantsforthewidthandheight,insteadofusingdirectlytheirnumericalvalues.This
givesthecodeabetterreadability,andallowschangesinthecodetobemadeeasilyinoneplace.
Arraysasparameters
Atsomepoint,wemayneedtopassanarraytoafunctionasaparameter.InC++,itisnotpossibletopasstheentire
blockofmemoryrepresentedbyanarraytoafunctiondirectlyasanargument.Butwhatcanbepassedinsteadisits
address.Inpractice,thishasalmostthesameeffect,anditisamuchfasterandmoreefficientoperation.
Toacceptanarrayasparameterforafunction,theparameterscanbedeclaredasthearraytype,butwithempty
brackets,omittingtheactualsizeofthearray.Forexample:
voidprocedure(intarg[])
Thisfunctionacceptsaparameteroftype"arrayofint"calledarg.Inordertopasstothisfunctionanarraydeclaredas:
intmyarray[40];
itwouldbeenoughtowriteacalllikethis:
procedure(myarray);
Hereyouhaveacompleteexample:
1 //arraysasparameters 51015
2 #include<iostream> 246810 Edit
3 usingnamespacestd;
4
5 voidprintarray(intarg[],intlength){
6 for(intn=0;n<length;++n)
7 cout<<arg[n]<<'';
8 cout<<'\n';
9 }
10
11 intmain()
12 {
13 intfirstarray[]={5,10,15};
14 intsecondarray[]={2,4,6,8,10};
15 printarray(firstarray,3);
16 printarray(secondarray,5);
17
http://www.cplusplus.com/doc/tutorial/arrays/ 3/4
8/14/2015 ArraysC++Tutorials
}
Inthecodeabove,thefirstparameter(intarg[])acceptsanyarraywhoseelementsareoftypeint,whateverits
length.Forthatreason,wehaveincludedasecondparameterthattellsthefunctionthelengthofeacharraythatwe
passtoitasitsfirstparameter.Thisallowstheforloopthatprintsoutthearraytoknowtherangetoiterateinthearray
passed,withoutgoingoutofrange.
Inafunctiondeclaration,itisalsopossibletoincludemultidimensionalarrays.Theformatforatridimensionalarray
parameteris:
base_type[][depth][depth]
Forexample,afunctionwithamultidimensionalarrayasargumentcouldbe:
voidprocedure(intmyarray[][3][4])
Noticethatthefirstbrackets[]areleftempty,whilethefollowingonesspecifysizesfortheirrespectivedimensions.This
isnecessaryinorderforthecompilertobeabletodeterminethedepthofeachadditionaldimension.
Inaway,passinganarrayasargumentalwayslosesadimension.Thereasonbehindisthat,forhistoricalreasons,arrays
cannotbedirectlycopied,andthuswhatisreallypassedisapointer.Thisisacommonsourceoferrorsfornovice
programmers.Althoughaclearunderstandingofpointers,explainedinacomingchapter,helpsalot.
Libraryarrays
Thearraysexplainedabovearedirectlyimplementedasalanguagefeature,inheritedfromtheClanguage.Theyarea
greatfeature,butbyrestrictingitscopyandeasilydecayintopointers,theyprobablysufferfromanexcessof
optimization.
Toovercomesomeoftheseissueswithlanguagebuiltinarrays,C++providesanalternativearraytypeasastandard
container.Itisatypetemplate(aclasstemplate,infact)definedinheader<array>.
Containersarealibraryfeaturethatfallsoutofthescopeofthistutorial,andthustheclasswillnotbeexplainedindetail
here.Sufficeittosaythattheyoperateinasimilarwaytobuiltinarrays,exceptthattheyallowbeingcopied(anactually
expensiveoperationthatcopiestheentireblockofmemory,andthustousewithcare)anddecayintopointersonly
whenexplicitlytoldtodoso(bymeansofitsmemberdata).
Justasanexample,thesearetwoversionsofthesameexampleusingthelanguagebuiltinarraydescribedinthis
chapter,andthecontainerinthelibrary:
languagebuiltinarray containerlibraryarray
#include<iostream> #include<iostream>
#include<array>
usingnamespacestd; usingnamespacestd;
intmain() intmain()
{ {
intmyarray[3]={10,20,30}; array<int,3>myarray{10,20,30};
for(inti=0;i<3;++i) for(inti=0;i<myarray.size();++i)
++myarray[i]; ++myarray[i];
for(intelem:myarray) for(intelem:myarray)
cout<<elem<<'\n'; cout<<elem<<'\n';
} }
Asyoucansee,bothkindsofarraysusethesamesyntaxtoaccessitselements:myarray[i].Otherthanthat,themain
differenceslayonthedeclarationofthearray,andtheinclusionofanadditionalheaderforthelibraryarray.Noticealso
howitiseasytoaccessthesizeofthelibraryarray.
Previous: Next:
Namevisibility Charactersequences
Index
Homepage|Privacypolicy
cplusplus.com,20002015Allrightsreservedv3.1
Spottedanerror?contactus
http://www.cplusplus.com/doc/tutorial/arrays/ 4/4