Is 2d array a double pointer? [duplicate] - Stack Overflow
文章推薦指數: 80 %
Is 2d array a double pointer? ... Therefore, to address element matrix[x][y] , you take the base address of matrix + x*4 + y (4 is the inner array ... Resultsfromthe2022DeveloperSurveyarenowavailable Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore Is2darrayadoublepointer?[duplicate] AskQuestion Asked 10years,9monthsago Modified 6years,1monthago Viewed 55ktimes 43 26 Thisquestionalreadyhasanswershere: Whycan'tweusedoublepointertorepresenttwodimensionalarrays? (6answers) Closed5yearsago. intmain() { matrix[2][4]={{11,22,33,99},{44,55,66,110}}; int**ptr=(int**)matrix; printf("%d%d",**matrix,*ptr); } Butwhena2-darrayispassedasaparameteritistypecastedinto(*matrix)[2].. whattypedoesthecompilerstorethisarrayas...isitstoringasa2-darrayoradoublepointeroranpointertoanarray..Ifitisstoringasanarrayhowdoesitinterpretsdifferentlyatdifferentsituationslikeabove.Pleasehelpmeunderstand. cmultidimensional-array Share Improvethisquestion Follow editedSep27,2012at11:56 JasonOrendorff 40.1k44goldbadges5959silverbadges9696bronzebadges askedSep28,2011at16:48 AngusAngus 11.4k2828goldbadges8484silverbadges146146bronzebadges 5 4 Pointersarenotarrays,andarraysarenotpointers.Arrays(whateverdimensiontheyhave)decayinto(single)pointerswhenpassedtofunctions. – AlexandreC. Sep28,2011at16:52 (int)matrixiskindofmeaningless.Itforcesmatrixtodecaytwicetoapointertoaninteger,buttheresultofcastingapointertoanintegerisundefined. – DavidSchwartz Sep28,2011at16:58 @DavidSchwartz:(int)matrixwoulddecaymatrixonce(nottwice),andtheresultisnotundefined,butimplementation-defined. – jpalecek Sep28,2011at17:17 @jpalecek:Implementation-definedmeanstheimplementationisfreetodowhateveritlikes.Soifyoudon'tknowtheimplementation,youhavenodefinition.Inthecontextwheretheimplementationisunknown,itisundefined.(Notintheformalsenseof'undefined',inthenormalsense.) – DavidSchwartz Sep28,2011at17:22 InC,donotcasttheresultofacalltomalloc(),realloc(),orcalloc()-itisunnecessaryandpotentiallymaskstheseriouserrorofamissingprototype. – mlp Jul15,2019at16:16 Addacomment | 4Answers 4 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 44 Is2darrayadoublepointer? No.Thislineofyourprogramisincorrect: int**ptr=(int**)matrix; Thisanswerdealswiththesametopic Ifyouwantconcreteimagehowmultidimensionalarraysareimplemented: Therulesformultidimensionalarraysarenotdifferentfromthoseforordinaryarrays,justsubstitutethe"inner"arraytypeaselementtype.Thearrayitemsarestoredinmemorydirectlyaftereachother: matrix:11223399445566110 -----------thefirstelementofmatrix ------------thesecondelementofmatrix Therefore,toaddresselementmatrix[x][y],youtakethebaseaddressofmatrix+x*4+y(4istheinnerarraysize). Whenarraysarepassedtofunctions,theydecaytopointerstotheirfirstelement.Asyounoticed,thiswouldbeint(*)[4].The4inthetypewouldthentellthecompilerthesizeoftheinnertype,whichiswhyitworks.Whendoingpointerarithmeticonasimilarpointer,thecompileraddsmultiplesoftheelementsize,soformatrix_ptr[x][y],yougetmatrix_ptr+x*4+y,whichisexactlythesameasabove. Thecastptr=(int**)matrixisthereforeincorrect.Foronce,*ptrwouldmeanapointervaluestoredataddressofmatrix,butthereisn'tany.Secondly,Thereisn'tapointertomatrix[1]anywhereinthememoryoftheprogram. Note:thecalculationsinthispostassumesizeof(int)==1,toavoidunnecessarycomplexity. Share Improvethisanswer Follow editedMay23,2017at11:47 CommunityBot 111silverbadge answeredSep28,2011at16:56 jpalecekjpalecek 45.9k77goldbadges9898silverbadges139139bronzebadges Addacomment | 12 No.Amultidimensionalarrayisasingleblockofmemory.Thesizeoftheblockistheproductofthedimensionsmultipliedbythesizeofthetypeoftheelements,andindexingineachpairofbracketsoffsetsintothearraybytheproductofthedimensionsfortheremainingdimensions.So.. intarr[5][3][2]; isanarraythatholds30ints.arr[0][0][0]givesthefirst,arr[1][0][0]givestheseventh(offsetsby3*2).arr[0][1][0]givesthethird(offsetsby2). Thepointersthearraydecaystowilldependonthelevel;arrdecaystoapointertoa3x2intarray,arr[0]decaystoapointertoa2elementintarray,andarr[0][0]decaystoapointertoint. However,youcanalsohaveanarrayofpointers,andtreatitasamultidimensionalarray--butitrequiressomeextrasetup,becauseyouhavetoseteachpointertoitsarray.Additionally,youlosetheinformationaboutthesizesofthearrayswithinthearray(sizeofwouldgivethesizeofthepointer).Ontheotherhand,yougaintheabilitytohavedifferentlysizedsub-arraysandtochangewherethepointerspoint,whichisusefuliftheyneedtoberesizedorrearranged.Anarrayofpointerslikethiscanbeindexedlikeamultidimensionalarray,eventhoughit'sallocatedandarrangeddifferentlyandsizeofwon'talwaysbehavethesamewaywithit.Astaticallyallocatedexampleofthissetupwouldbe: int*arr[3]; intaa[2]={10,11}, ab[2]={12,13}, ac[2]={14,15}; arr[0]=aa; arr[1]=ab; arr[2]=ac; Aftertheabove,arr[1][0]is12.Butinsteadofgivingtheintfoundat1*2*sizeof(int)bytespastthestartaddressofthearrayarr,itgivestheintfoundat0*sizeof(int)bytespasttheaddresspointedtobyarr[1].Also,sizeof(arr[0])isequivalenttosizeof(int*)insteadofsizeof(int)*2. Share Improvethisanswer Follow editedMay21,2016at16:21 answeredSep28,2011at19:18 DmitriDmitri 8,91022goldbadges2525silverbadges3232bronzebadges Addacomment | 4 InC,there'snothingspecialyouneedtoknowtounderstandmulti-dimensionalarrays.Theyworkexactlythesamewayasiftheywereneverspecificallymentioned.Allyouneedtoknowisthatyoucancreateanarrayofanytype,includinganarray. Sowhenyousee: intmatrix[2][4]; Justthink,"matrixisanarrayof2things--thosethingsarearraysof4integers".Allthenormalrulesforarraysapply.Forexample,matrixcaneasilydecayintoapointertoitsfirstmember,justlikeanyotherarray,whichinthiscaseisanarrayoffourintegers.(Whichcan,ofcourse,itselfdecay.) Share Improvethisanswer Follow answeredSep28,2011at17:01 DavidSchwartzDavidSchwartz 174k1717goldbadges200200silverbadges267267bronzebadges Addacomment | 1 Ifyoucanusethestackforthatdata(smallvolume)thenyouusuallydefinethematrix: intmatrix[X][Y] Whenyouwanttoallocateitintheheap(largevolume),theyouusuallydefinea: int**matrix=NULL; andthenallocatethetwodimensionswithmalloc/calloc. Youcantreatthe2darrayasint**butthatisnotagoodpracticesinceitmakesthecodelessreadable.Otherthenthat **matrix==matrix[0][0]istrue Share Improvethisanswer Follow answeredSep28,2011at17:00 long404long404 97788silverbadges1212bronzebadges 1 intmatrix[X][Y]isstaticallocation,soyoualsoneedtoknowX,Ydimensionsatcompiletime. – joepol Mar10,2020at21:24 Addacomment | Highlyactivequestion.Earn10reputation(notcountingtheassociationbonus)inordertoanswerthisquestion.Thereputationrequirementhelpsprotectthisquestionfromspamandnon-answeractivity. Nottheansweryou'relookingfor?Browseotherquestionstaggedcmultidimensional-arrayoraskyourownquestion. TheOverflowBlog Askedandanswered:theresultsforthe2022Developersurveyarehere! LivingontheEdgewithNetlify(Ep.456) FeaturedonMeta Testingnewtrafficmanagementtool Upcomingcleanupofduplicatevotes AskWizardTestResultsandNextSteps Trending:Anewanswersortingoption Updatedbuttonstylingforvotearrows:currentlyinA/Btesting Linked 36 Whycan'tweusedoublepointertorepresenttwodimensionalarrays? 2 Isamatrixintmat[5][5]thesamethingasanint**? 3 pointersandmulti-dimensionalarrays 3 Whatisthedifferencebetweenthistwodeclarations"int**matrix"and"intmatrix[][]"? 2 **operatordoesnotworkon2-dimensionalarrayasparameter 0 Warning:assignmentfromincompatiblepointertype 2 Expected'char**'butargumentisoftype'char(*)[25]' 1 Pointertoanarrayanddoublepointer 1 error:assigningto'int**'fromincompatibletype'int[][] 1 Howtoput2-dimensionalArray'spointertothefunctionastheparameter Seemorelinkedquestions Related 1278 HowdoIdeterminethesizeofmyarrayinC? 1320 HowcanIcreateatwodimensionalarrayinJavaScript? 3217 ImproveINSERT-per-secondperformanceofSQLite 1331 HowtoSortaMulti-dimensionalArraybyValue 1 Passinganarrayasdoublepointerincwarningmessage 3 PointertoIntegerArrayversusDoublePointertoInteger 0 Isthereawaytoprintapointerwith%xargument HotNetworkQuestions Whydoprogunandantiabortion(andviceversa)viewsgotogetherintheUSA? Whatisthenameofthiscreature? SeparationoftheChurchandStateinHinduism Whydoesthegovernmentnotintroduceanamendmenttotheconstitutiontoallowabortion? WhyareRoevWadeandPlannedParenthoodvCaseyabbreviatedasRoeandCasey? Whatdoes"verynature"ofaservantmeaninPhilippians2:7? HotWaterHeaterReliefValveLeakage ResourcesonthestationarySchrödingerequationwiththesolitonpotential Whydoesafemale-femalecouplerbreaktheUSB-Cstandard? FromwhichepisodeofTOSwasthisgifofSpockpullingclothesoutofadresserdrawertaken? WhydoIgetaccostedfortakingphotosofawarmemorial? Pythoncodetocheckstockstatusataretailer Whatisthepurposeofindexingthemempoolbythesefivecriteria? Hypothetically,canearlyhumansdomesticategiantantssimilartowolves?Maybeevenassistthemintheagriculturalrevolution? WillThisVoltageDividerKeepMyMosfetOn? HowcanIaddalayerofmeaningtoanevilcampaign? hashtagkepmapinvimintexfile InMagic,areyouallowedtorevealwhatcardsyouhavedraftedtostopothersfromdraftingthesamecolors? Firsttimeflyingwithcarryononly.CanIcarrydoubleedgedrazorbladeswithme? Dosymmetricalairfoilsgenerateinduceddrag? Whytouseudevruletoinsurepersistentnaming/permissioninsteadofmknod? IterativeSmallestComplement HowshallIproceedifmycarmaycontainillegaldrugsanddrugparaphernaliabeforeenteringCanadabycarfromtheUS? WhatarethemainargumentsusedbyChristianpro-liferstojustifytheirstanceagainstabortion? morehotquestions lang-c Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings
延伸文章資訊
- 1Arrays and pointers in C - Ibiblio
QED Why a double pointer can't be used as a 2D array? ... The 2D array is "equivalent" to a "poin...
- 2Pointer to an Array | Array Pointer - GeeksforGeeks
- 3How to make 2d array using double pointer - Quora
A double pointer is basically a pointer to pointer. A pointer denotes the address of a particular...
- 4Double pointer · parallel_processing
陣列的指標是指有許多指標,每個指標指向固定長度的陣列. /* pointer to array of 20 integers * 這邊*pAry是指向每個row的第一個元素,而每 ...
- 5Lecture 06 2D Arrays & pointer to a pointer(**)
Accessing a 2D array using pointers. •. ** or pointer to a pointer. •. Passing pointer to a funct...