C Dynamic Memory Allocation Using malloc ... - Programiz

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

malloc() CourseIndex ExploreProgramiz Python JavaScript SQL C C++ Java Kotlin Swift C# DSA LearnCpractically andGetCertified. ENROLL PopularTutorials DataTypesinC Cif...elseStatement CforLoop ArraysinCProgramming PointersinC StartLearningC PopularExamples Checkodd/evennumber Findrootsofaquadraticequation PrintPyramidsandPatterns Checkprimenumber PrinttheFibonacciseries ExploreCExamples ReferenceMaterials string.h math.h ctype.h Viewall LearningPaths Challenges LearnCInteractively TryforFree Courses BecomeaCMaster BecomeaPythonMaster BecomeaJavaMaster ViewallCourses Python JavaScript SQL C C++ Java Kotlin Swift C# DSA LearnCpractically andGetCertified. ENROLLFORFREE! PopularTutorials DataTypesinC Cif...elseStatement CforLoop ArraysinCProgramming PointersinC StartLearningC AllCTutorials ReferenceMaterials string.h math.h ctype.h Viewall Python JavaScript C C++ Java Kotlin LearnCpractically andGetCertified. ENROLLFORFREE! PopularExamples Checkodd/evennumber Findrootsofaquadraticequation PrintPyramidsandPatterns Checkprimenumber PrinttheFibonacciseries AllCExamples InteractiveCCourse CIntroduction Keywords&Identifier Variables&Constants CDataTypes CInput/Output CComments COperators CIntroductionExamples CFlowControl Cif...else CforLoop CwhileLoop Cbreakandcontinue Cswitch...case CProgramminggoto ControlFlowExamples CFunctions CProgrammingFunctions CUser-definedFunctions CFunctionTypes CRecursion CStorageClass CFunctionExamples CProgrammingArrays CProgrammingArrays CMulti-dimensionalArrays CArrays&Function CProgrammingPointers CProgrammingPointers CPointers&Arrays CPointersAndFunctions CMemoryAllocation Array&PointerExamples CProgrammingStrings CProgrammingString CStringFunctions CStringExamples StructureAndUnion CStructure CStruct&Pointers CStruct&Function CUnions CstructExamples CProgrammingFiles CFilesInput/Output CFilesExamples AdditionalTopics CEnumeration CPreprocessors CStandardLibrary CProgrammingExamples RelatedTopics FindLargestNumberUsingDynamicMemoryAllocation StoreDatainStructuresDynamically CstructsandPointers CUnions FindtheSizeofint,float,doubleandchar CPointers CDynamicMemoryAllocation Inthistutorial,you'lllearntodynamicallyallocatememoryinyourCprogramusingstandardlibraryfunctions:malloc(),calloc(),free()andrealloc(). Asyouknow,anarrayisacollectionofafixednumberofvalues.Oncethesizeofanarrayisdeclared,youcannotchangeit. Sometimesthesizeofthearrayyoudeclaredmaybeinsufficient.Tosolvethisissue,youcanallocatememorymanuallyduringrun-time.ThisisknownasdynamicmemoryallocationinCprogramming. Toallocatememorydynamically,libraryfunctionsaremalloc(),calloc(),realloc()andfree()areused.Thesefunctionsaredefinedintheheaderfile. Cmalloc() Thename"malloc"standsformemoryallocation. Themalloc()functionreservesablockofmemoryofthespecifiednumberofbytes.And,itreturnsapointerofvoidwhichcanbecastedintopointersofanyform. Syntaxofmalloc() ptr=(castType*)malloc(size); Example ptr=(float*)malloc(100*sizeof(float)); Theabovestatementallocates400bytesofmemory.It'sbecausethesizeoffloatis4bytes.And,thepointerptrholdstheaddressofthefirstbyteintheallocatedmemory. TheexpressionresultsinaNULLpointerifthememorycannotbeallocated. Ccalloc() Thename"calloc"standsforcontiguousallocation. Themalloc()functionallocatesmemoryandleavesthememoryuninitialized,whereasthecalloc()functionallocatesmemoryandinitializesallbitstozero. Syntaxofcalloc() ptr=(castType*)calloc(n,size); Example: ptr=(float*)calloc(25,sizeof(float)); Theabovestatementallocatescontiguousspaceinmemoryfor25elementsoftypefloat. Cfree() Dynamicallyallocatedmemorycreatedwitheithercalloc()ormalloc()doesn'tgetfreedontheirown.Youmustexplicitlyusefree()toreleasethespace. Syntaxoffree() free(ptr); Thisstatementfreesthespaceallocatedinthememorypointedbyptr. Example1:malloc()andfree() //Programtocalculatethesumofnnumbersenteredbytheuser #include #include intmain(){ intn,i,*ptr,sum=0; printf("Enternumberofelements:"); scanf("%d",&n); ptr=(int*)malloc(n*sizeof(int)); //ifmemorycannotbeallocated if(ptr==NULL){ printf("Error!memorynotallocated."); exit(0); } printf("Enterelements:"); for(i=0;i #include intmain(){ intn,i,*ptr,sum=0; printf("Enternumberofelements:"); scanf("%d",&n); ptr=(int*)calloc(n,sizeof(int)); if(ptr==NULL){ printf("Error!memorynotallocated."); exit(0); } printf("Enterelements:"); for(i=0;i #include intmain(){ int*ptr,i,n1,n2; printf("Entersize:"); scanf("%d",&n1); ptr=(int*)malloc(n1*sizeof(int)); printf("Addressesofpreviouslyallocatedmemory:\n"); for(i=0;i



請為這篇文章評分?