How to Create an Array Using Malloc() in C Programming

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

In c programming, the array is used to store a range of values of the same data type and it occupies some space in memory which can be either static or ... Incprogramming,thearrayisusedtostorearangeofvaluesofthesamedatatypeanditoccupiessomespaceinmemorywhichcanbeeitherstaticordynamic.Themallocisafunctionusedinthecprogrammingfordynamicmemoryallocation. Inthisarticle,wewilllearnaboutthemallocfunctiontocreateanarrayincprogramming. Whatisamalloc()inCprogramming Thedynamicmemoryisallocatedtotheprogramduringitsexecutionaccordingtothespaceneededbyit.Instaticmemory,thefixedmemoryisallocatedtotheprogrambeforeexecutionoftheprogramwhichhasthefollowingdisadvantages: Thearraydeclaredwiththefixedsizewilloccupythefixedsizeonthesystemmemory Ifthearrayhasvalueslessthanthesizedeclared,thefreespacewillbewastageandcannotbeusedbyanotherprogram Ifthearrayhasvaluesmorethanthesizedeclared,theprogrammaygiveerrors Toavoidthesedisadvantages,wewillusethedynamicmemoryallocationschemeasthisschemewillassignthememoryoftheblockneededbytheprogramduringitsexecution.Dynamicmemoryhasdifferentfunctionsusedasapointertowardstheprogram. Themalloc()functionstandsfor“memoryallocation”andisusedfordynamicmemoryallocationwhileexecutionoftheprogram.Whenthemalloc()functioniscalled,itsendsarequestofamemoryblocktotheheap(itisamemorysegmentwherethememoryisallocatedrandomly).Iftheheaphasmemoryequivalenttothatmemoryblock,itwillaccepttherequestandassignthatsizetothemalloc()functionagainstitsrequest,andifithasnomemorythenitwillreturnthenullvalue.Whenwearedonewiththememoryblock,wecanclearitbyusingthefree()functionsothatthememoryblockcangetfreeandbeusedbytheotherprograminstructions.Fordynamicmemoryallocation,wehavetoincludethe“stdlib.h”inheaderfilesandthegeneralsyntaxofusingthemallocfunctionis: 1$pointer=(castType*)malloc(size); Wecanuseanyvariableinsteadof“pointer”thenwecanreplacethe“castType”withthedatatypewhosevaluesaregoingtostoreinthearray.Thenusethemalloc()functionandmentionthesizeofthememoryweneeded. HowtousemallocfunctioninCprogrammingtocreateanarray Forabetterunderstandingofthecreationofanarrayusingthemalloc()function,wewillcreateaprogram.TousethecprogramminginLinux,wehavetoinstalltheGCCcompilerusingthecommand: 1$sudoaptinstallgcc Createatextfileusingthenanoeditor: 1$nanomyfile.c Typethefollowingcode: 123456789101112131415161718192021222324252627#include#include intmain(void) { intsize,i,*my_array; printf(“\nPleasetypethesizeofarray:”); scanf(“%d”,&size); my_array=(int*)malloc(size*sizeof(int)); printf(“\nEnterthevaluesofArray: ”); for(i=0;i



請為這篇文章評分?