C Language: malloc function (Allocate Memory Block)

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

The malloc function returns a pointer to the beginning of the block of memory. If the block of memory can not be allocated, the malloc function will return a ... Advertisements CLanguage:mallocfunction(AllocateMemoryBlock) IntheCProgrammingLanguage,themallocfunctionallocatesablockofmemoryforanarray,butitdoesnotcleartheblock.Toallocateandcleartheblock,usethecallocfunction. Syntax ThesyntaxforthemallocfunctionintheCLanguageis: void*malloc(size_tsize); ParametersorArguments size Thesizeoftheelementsinbytes. Returns Themallocfunctionreturnsapointertothebeginningoftheblockofmemory.Iftheblockofmemorycannotbeallocated,themallocfunctionwillreturnanullpointer. RequiredHeader IntheCLanguage,therequiredheaderforthemallocfunctionis: #include AppliesTo IntheCLanguage,themallocfunctioncanbeusedinthefollowingversions: ANSI/ISO9899-1990 mallocExample Let'slookatanexampletoseehowyouwouldusethemallocfunctioninaCprogram: /*ExampleusingmallocbyTechOnTheNet.com*/ /*ThesizeofmemoryallocatedMUSTbelargerthanthedatayouwillputinit*/ #include #include #include intmain(intargc,constchar*argv[]) { /*Definerequiredvariables*/ char*ptr; size_tlength; /*Definetheamountofmemoryrequired*/ length=50; /*Allocatememoryforourstring*/ ptr=(char*)malloc(length); /*Checktoseeifweweresuccessful*/ if(ptr==NULL) { /*Wewerenotsodisplayamessage*/ printf("Couldnotallocaterequiredmemory\n"); /*Andexit*/ exit(1); } /*Copyastringintotheallocatedmemory*/ strcpy(ptr,"CmallocatTechOnTheNet.com"); /*Displaythecontentsofmemory*/ printf("%s\n",ptr); /*Freethememoryweallocated*/ free(ptr); return0; } Whencompiledandrun,thisapplicationwilloutput: CmallocatTechOnTheNet.com SimilarFunctions OtherCfunctionsthataresimilartothemallocfunction: callocfunction freefunction reallocfunction Shareon: Advertisements Home|AboutUs|ContactUs|Testimonials|Donate Whileusingthissite,youagreetohavereadandacceptedourTermsofServiceandPrivacyPolicy. Copyright©2003-2022TechOnTheNet.com.Allrightsreserved.



請為這篇文章評分?