2D Array and Double Pointer in C | Toolbox Tech - Spiceworks

文章推薦指數: 80 %
投票人數:10人

In expressions the name of an array is converted to a pointer to its first element. As arr is a two-dimensional array when arr is converted to int ( * )[4]. EXPLORE FOLLOWUS Facebook Twitter LinkedIn RSS Youtube Home News&Insights News&InsightsHome Innovation ITCareers&Skills Cloud CyberSecurity FutureofWork AllCategories Marketing HR Finance Community Askquestion CommunityHome SpiceworksOriginals Cloud Collaboration Networking WaterCooler Windows Allforums How-Tos Scripts Vendors Meetups Reviews OnlineEvents Login Join Login Join Toolbox.comhasbecomeSpiceworksNews&Insights.Here'swhy. Programming 2DArrayandDoublePointerinC 8.77KviewsJuly25,2020 AnirbanRoy November18,2011 0Comments “#include intmain() { intarr[][4]={ {12,23,34,45}, {56,67,78,89} }; int**ptr=NULL; ptr=(int**)arr; printf(“nThearrayfirstelementAccess&percnt;d&percnt;d”,arr[0][0],*ptr); ptr++; printf(“nThearrayfirstelementAccess&percnt;d&percnt;d”,arr[0][0],*ptr); printf(“nThearrayfirstelementAccess&percnt;d&percnt;d”,arr[0][0],*(*(ptr+0)+0)); printf(“nThearrayfirstelementAccess&percnt;d&percnt;d”,arr[0][0],**ptr); return0; } //itisshowingfor**ptr CananyonepleaseexplainmewhyIcannotaccess2Darrayusingdoublepointer //forthislineptr=(int**)arrcompilerdoesnotcomplainbutforaccessingitisshowing //problemfordoubleindirection.” 8 Answers AnuroopJesu PostedNovember18,2011 0 Comments Hianirban_roy, BeforeIgiveanyexplanationletmegivesomeinformationonthehowtheelementsarestoredinthearray2D intarr[][4]={{12,23,34,45},{56,67,78,89}}; –Alltheelementsintheabovearrayarestoredinthesequentialmemoryaddressandthisisequivalenttointarr[]={12,23,34,45,56,67,78,89}; SoMultidimensionalarraysarerepresentedasthesingledimensionandcompleteabstractionisprovidedbycompilertoprogrammer Nowcomingbacktothedoublepointer,thedoublepointercanonlystoretheaddressofthepointersoifyoustillwanttoaccessthe2Darrayusingdoublepointerthenthiscanbedoneasgivebelow #includeintmain(){intarr[][4]={{12,23,34,45},{56,67,78,89},{12,23,34,45},{56,67,78,89},{56,67,78,89},{12,23,34,45},};int**ptr=NULL;ptr=&arr; inti=0,j=0;for(;i<5;i++){for(;j<4;j++)printf(“[&percnt;d][&percnt;d][&percnt;d][&percnt;d]rn”,i,j,arr[j],*(ptr+(i*4)+j));j=0;}} Hopethishelps. WithWarmRegardsJesuAnuroopSuresh “Anyintelligentfoolcanmakethingsbigger,morecomplex,andmoreviolent.Ittakesatouchofgenius—andalotofcourage—tomoveintheoppositedirection.”“Anyonewhohasnevermadeamistakehasnevertriedanythingnew.” PaulPedant PostedNovember18,2011 0 Comments Yourint**p=NULLisfine–itdoesnotclashwithanything. Yourcastp=(int**)arriscompilablebecauseyourcastover-ridesthecompiler.Itassertsthatthefirstelementofarrisapointertoint,althoughitisnot.Ifyouhavetocaststuff,itusuallymeansyouarehidingaproblem. Whenyoudereferenceptwice,ittriestouse12asanint*,andbreaks. AnirbanRoy PostedNovember21,2011 0 Comments ThankyourforyourresponsebutIamstuckwithonemoreconfusionrelatingtothis Hereisthecode #includeintmain(){{12,23,34,45},{56,67,78,89}};int**ptr=(int**)arr;printf(“&percnt;d&percnt;d”,**arr,*ptr);ptr++;printf(“&percnt;d&percnt;d”,**arr,*ptr); return0;}ifdereferncingtwicemeanstotryingtouse12asanint*,thenhow**arrworksfinehere…. Thanks Anirban PaulPedant PostedNovember22,2011 0 Comments Don’tunderstand“worksfine”.Whatoutputdoyouget,andwhatwouldyouexpect. Presumablyacompileerror,asneitherarrnorptraredefinednow. Noneither,soyoumighthaveexpectedtooutput12231223anyway. JohnNawrocki PostedNovember23,2011 0 Comments Thismightbewhatyouaretryingtoaccomplish intmain(){intarr[][4]={{12,23,34,45},{56,67,78,89}};int**ptr,i,x;ptr=(int**)arr;for(x=0;x<2;x++){for(i=0;i<4;++i)printf(“Thearray[&percnt;d]element[&percnt;d]Access&percnt;dn”,x,i,*(ptr++));}return0; PaulPedant PostedNovember23,2011 0 Comments @Anirban, Thisiswhatisgoingoninyourcodesample.Firstthebitswitharr. Thecompilertreatsthenamearrastheaddressofa2-darray. ThereisanaddressequivalenceinCbetweenindexingandaddressdereference.X[2]and*(X+2)areidentical(sois*(2+X)too). SoX[0][0]and**Xarealsoidentical.Toindexbyanythingotherthan0,youhavetobrackettheprecedence.Forexample,X[1][3]isidenticalto:*(*(arr+1)+3);that’snottooeasytoread. Whenyouassigntoint**ptr=(int**)arr;thevalueassignedistheaddressofthearray.Youhavetoldthecompilerthatptristobetreatedasapointertoapointertoanint(whichitisnot),andtostopitwarningyou,youhavealsocastthevalue.Rememberacastdoesnotchangethebitscopied–itjusttellsthecompilertoacceptthecopywithoutarguing. Youthenincrementptr++;thisincrementsbythesizeoftheobjectwhichptrpointsto,thatissizeof(int*). Nowithappensonyoursystemthatanint*andanintareboth32bits.That’snottrueinWindowssmallmemorymodel(addresses16-bitandinteger32-bit).Andit’snottrueonmyLinux64-bitsystem–address64bitsandint32-bits.Eitherofthesewouldfailonthiscode. Thenyousend*ptrtoprintf.Well,printfdoesnotdoanytypechecking.*ptrjustdereferencesptronce.Itstartedoffpointingtoarr,andafterincrementingitnowpoints32bitsalongarr,whichiswhyitreturnsthenextvalue.Butit’stheresultof3bugscancellingout–thecastofarr,theincrementofa**,andpassinganint*toa&percnt;dinprintf. vlad.moscow PostedDecember7,2011 0 Comments Togetansweronyourquestionletconsiderwhatactionstakeplacewhenexpression**arrisused.Inexpressionsthenameofanarrayisconvertedtoapointertoitsfirstelement.Asarrisatwo-dimensionalarraywhenarrisconvertedtoint(*)[4].Whenyouapplyderederencing*arryougetone-dimensionalarraywhichcorrespondstothefirstrowoftheoriginaltwo-dimensionalarray.Againinexpressionsitiscomvertedtoapointertoitsfirstelementi.e.toint*.Whenyouapplydereferencingonemoreyougetarr[0][0]. Anonymous PostedDecember7,2011 0 Comments DearJohnNawrockiYoucanstoreaddressofa2-darrayasfollows: inta[2][3];int(*p)[3]=a;//pispointertorow/blockofsize3//inthesamewayintb[2][3][6];int(*q)[3][6]=b;//qisapointertoablockofsize3*6 Popular 1 Top10DevOpsCertificationsandCoursesin2022 2 TechSalariesin2022:WhytheSixFigurePayMakesTechiesFeelUnderpaid 3 Top10CI/CDToolsin2022 RecentPosts MailBoxesTimes RecentCommentsBinaJacobonTheCriticalRoleofSeniorEmployeesinL&D:MentoringtheNextGenerationtsadeeb@hotmail.comonGoogleMapChallengeInIstanbulPavelSoukuponWANTED:Single,SuccessfulSQLForFIFOCOGSnaganarasimha@infostellar.comonTop10PrivilegedAccessManagementSolutionsin2021SteveJonesonFromCOBOLtoJava:WhyandHowtoMaketheSwitch Toolboxisnow OnJune22,ToolboxwillbecomeSpiceworksNews&Insights JointheSpiceworksCommunity WeencourageyoutoreadourupdatedPRIVACYPOLICYandCOOKIEPOLICY. ×



請為這篇文章評分?