Sei sulla pagina 1di 3

3/24/2014 C dynamically growing array - Stack Overflow

http://stackoverflow.com/questions/3536153/c-dynamically-growing-array 1/3
Balkania
205 1 4 6
4 Answers
Ihaveaprogramthatreadsa"raw"listofingameentities,andIintendtomakeanarrayholdingan
indexnumber(int)ofanindeterminatenumberofentities,forprocessingvariousthings.Iwouldliketo
avoidusingtoomuchmemoryorCPUforkeepingsuchindexes...
AquickanddirtysolutionIusesofaristodeclare,inthemainprocessingfunction(localfocus)the
arraywithasizeofthemaximumgameentities,andanotherintegertokeeptrackofhowmanyhave
beenaddedtothelist.Thisisn'tsatisfactory,aseverylistholds3000+arrays,whichisn'tthatmuch,but
feelslikeawaste,sinceI'llpossibleusethesolutionfor67listsforvaryingfunctions.
Ihaven'tfoundanyC(notC++orC#)specificsolutionstoachievethis.Icanusepointers,butIamabit
afraidofusingthem(unlessit'stheonlypossibleway).
Thearraysdonotleavethelocalfunctionscope(theyaretobepassedtoafunction,thendiscarded),in
casethatchangesthings.
Ifpointersaretheonlysolution,howcanIkeeptrackofthemtoavoidleaks?
c dynamicarrays
askedAug21'10at3:23
Thisisa(very,verysmall)probleminC,buthowdidyoumissalltheC++andC#solutionsforthis?
IgnacioVazquezAbramsAug21'10at3:28
4 "Ifpointersaretheonlysolution,howcanIkeeptrackofthemtoavoidleaks?"Care,attention,andvalgrind.
ThisisexactlywhypeoplearesoafraidifCinthefirstplace.ChrisLutzAug21'10at4:00
4 YoucannotuseCeffectivelywithoutusingpointers.Don'tbeafraid.qrdlAug21'10at4:17
withoutbiglibsonlyonefunctionforallalsoforstructseg:stackoverflow.com/questions/3456446/
user411313Aug21'10at6:45
Icanusepointers,butIamabitafraidofusingthem.
Ifyouneedadynamicarray,youcan'tescapepointers.Whyareyouafraidthough?Theywon'tbite(as
longasyou'recareful,thatis).There'snobuiltindynamicarrayinC,you'lljusthavetowriteone
yourself.InC++,youcanusethebuiltin std::vector class.C#andjustabouteveryotherhighlevel
languagealsohavesomesimilarclassthatmanagesdynamicarraysforyou.
Ifyoudoplantowriteyourown,here'ssomethingtogetyoustarted:mostdynamicarray
implementationsworkbystartingoffwithanarrayofsome(small)defaultsize,thenwheneveryourun
outofspacewhenaddinganewelement,doublethesizeofthearray.Asyoucanseeintheexample
below,it'snotverydifficultatall:(I'veomittedsafetychecksforbrevity)
typedefstruct{
int*array;
size_tused;
size_tsize;
}Array;
voidinitArray(Array*a,size_tinitialSize){
a>array=(int*)malloc(initialSize*sizeof(int));
a>used=0;
a>size=initialSize;
}
voidinsertArray(Array*a,intelement){
if(a>used==a>size){
a>size*=2;
a>array=(int*)realloc(a>array,a>size*sizeof(int));
}
C dynamically growing array


1 1

help

addcomment
3/24/2014 C dynamically growing array - Stack Overflow
http://stackoverflow.com/questions/3536153/c-dynamically-growing-array 2/3
user283145 casablanca
39.1k 1 40 79
Wolph
25.9k 42 70
}
a>array[a>used++]=element;
}
voidfreeArray(Array*a){
free(a>array);
a>array=NULL;
a>used=a>size=0;
}
Usingitisjustassimple:
Arraya;
inti;
initArray(&a,5);//initially5elements
for(i=0;i<100;i++)
insertArray(&a,i);//automaticallyresizesasnecessary
printf("%d\n",a.array[9]);//print10thelement
printf("%d\n",a.used);//printnumberofelements
freeArray(&a);
editedAug31'13at22:18 answeredAug21'10at4:01
1 Thanksforthesamplecode.Iimplementedthespecificfunctionusingabigarray,butwillimplementother
similarthingsusingthis,andafterIgetitcontrolled,changetheothersback:) Balkania Aug21'10at
11:02
1 Thanksalotforthecode.A removeArray methodthatgetsridofthelastelementwouldalsobeneat.If
youallowit,Iwilladdittoyourcodesample.brimboriumJan14'13at16:15
2 %dandsize_t...bitofanonothere.IfyouuseC99orlater,cantakeadvantageoftheadditionof%z
RandyHowardApr28'13at7:30
ThereareacoupleofoptionsIcanthinkof.
1. LinkedList.Youcanusealinkedlisttomakeadynamicallygrowingarraylikething.Butyouwon't
beabletodoarray[100]withouthavingtowalkthrough199first.Anditmightnotbethathandy
foryoutouseeither.
2. Largearray.Simplycreateanarraywithmorethanenoughspaceforeverything
3. Resizingarray.Recreatethearrayonceyouknowthesizeand/orcreateanewarrayeverytime
yourunoutofspacewithsomemarginandcopyallthedatatothenewarray.
4. LinkedListArraycombination.Simplyuseanarraywithafixedsizeandonceyourunoutofspace,
createanewarrayandlinktothat(itwouldbewisetokeeptrackofthearrayandthelinktothe
nextarrayinastruct).
Itishardtosaywhatoptionwouldbebestinyoursituation.Simplycreatingalargearrayisofcourse
oneoftheeasiestsolutionsandshouldn'tgiveyoumuchproblemsunlessit'sreallylarge.
answeredAug21'10at3:31
Howdoessevenarraysof3264integerssoundforamodernish2Dgame?IfIamjustbeingparanoid,the
solutionwouldbelargearray. Balkania Aug21'10at3:34
1 Both#1and#4hererequireusingpointersanddynamicmemoryallocationanyhow.Isuggestusing
realloc with#3allocatethearrayanormalsize,andthengrowitwheneveryourunout. realloc will
handlecopyingyourdataifnecessary.AsfortheOP'squestiononmemorymanagement,youjustneedto
malloc onceatthestart, free onceattheend,and realloc eachtimeyourunoutofroom.It'snot
toobad.BorealidAug21'10at3:34
@Balkania:sevenarraysof3264integersisahairunder100KB.That'snotverymuchmemoryatall.
BorealidAug21'10at3:35
@Borealid:Hoh,Ishouldreallyforgetmyancientquickbasictimes:PI'lltrytogoforthelargearraytotest
thesystem,anddareventuringintothemalloclater,I'llneedtoreadabit. Balkania Aug21'10at3:38
@Balkania: 7*3264*32bit soundslike 91.39kilobytes .Notthatmuchbyanystandardthese
days)WolphAug21'10at3:57
GlibhasagoodsolutionforCwithreferencecountingtohelpwithmemorymanagement,andisfree
andcrossplatform.Ifyouwantsomethingmorebasic,youshouldlookatrealloc.Cprogrammingis
really,reallyhardtodowithoutpointers.Mayaswellstartgettingcomfortablewiththemnow.
addcomment
addcomment
3/24/2014 C dynamically growing array - Stack Overflow
http://stackoverflow.com/questions/3536153/c-dynamically-growing-array 3/3
KarlBielefeldt
14k 3 16 43
LieRyan
22k 4 35 80
really,reallyhardtodowithoutpointers.Mayaswellstartgettingcomfortablewiththemnow.
answeredAug21'10at3:51
Whenyou'resaying
makeanarrayholdinganindexnumber(int)ofanindeterminatenumberofentities
you'rebasicallysayingyou'reusing"pointers",butonewhichisaarraywidelocalpointerinsteadof
memorywidepointer.Sinceyou'reconceptuallyalreadyusing"pointers"(i.e.idnumbersthatrefersto
anelementinanarray),whydon'tyoujustuseregularpointers(i.e.idnumbersthatreferstoan
elementinthebiggestarray:thewholememory).
Insteadofyourobjectsstoringaresourceidnumbers,youcanmakethemstoreapointerinstead.
Basicallythesamething,butmuchmoreefficientsinceweavoidturning"array+index"intoa"pointer".
Pointersarenotscaryifyouthinkofthemasarrayindexforthewholememory(whichiswhatthey
actuallyare)
answeredAug21'10at3:44
Not the answer you're looking for? Browse other questions tagged c dynamicarrays
or ask your own question.
addcomment
addcomment

Potrebbero piacerti anche