malloc() Function in C library with EXAMPLE - Guru99

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

The malloc() function stands for memory allocation. It is a function which is used to allocate a block of memory dynamically. Skiptocontent WhatismallocinC? Themalloc()functionstandsformemoryallocation.Itisafunctionwhichisusedtoallocateablockofmemorydynamically.Itreservesmemoryspaceofspecifiedsizeandreturnsthenullpointerpointingtothememorylocation.Thepointerreturnedisusuallyoftypevoid.Itmeansthatwecanassignmallocfunctiontoanypointer. Syntax ptr=(cast_type*)malloc(byte_size); Here, ptrisapointerofcast_type. Themallocfunctionreturnsapointertotheallocatedmemoryofbyte_size. Example:ptr=(int*)malloc(50) Whenthisstatementissuccessfullyexecuted,amemoryspaceof50bytesisreserved.Theaddressofthefirstbyteofreservedspaceisassignedtothepointerptroftypeint. Consideranotherexampleofmallocimplementation: #include intmain(){ int*ptr; ptr=malloc(15*sizeof(*ptr));/*ablockof15integers*/ if(ptr!=NULL){ *(ptr+5)=480;/*assign480tosixthinteger*/ printf("Valueofthe6thintegeris%d",*(ptr+5)); } } Output: Valueofthe6thintegeris480 Noticethatsizeof(*ptr)wasusedinsteadofsizeof(int)inordertomakethecodemorerobustwhen*ptrdeclarationistypecastedtoadifferentdatatypelater. Theallocationmayfailifthememoryisnotsufficient.Inthiscase,itreturnsaNULLpointer.So,youshouldincludecodetocheckforaNULLpointer. Keepinmindthattheallocatedmemoryiscontiguousanditcanbetreatedasanarray.Wecanusepointerarithmetictoaccessthearrayelementsratherthanusingbrackets[].Weadvisetouse+torefertoarrayelementsbecauseusingincrementation++or+=changestheaddressstoredbythepointer. Mallocfunctioncanalsobeusedwiththecharacterdatatypeaswellascomplexdatatypessuchasstructures. YouMightLike: FunctionsPointersinCProgrammingwithExamples BitwiseOperatorsinC:AND,OR,XOR,Shift&Complement 13BESTCProgrammingBooksforBeginners(2022Update) calloc()FunctioninCLibrarywithProgramEXAMPLE realloc()FunctioninCLibrary:Howtouse?Syntax&Example Postnavigation ReportaBug Previous PrevNextContinue Scrolltotop ToggleMenuClose Searchfor: Search



請為這篇文章評分?