Home > Article > Backend Development > Explain dynamic memory allocation in C language with an example
Using C programming, find the sum of n numbers entered by the user using dynamically allocated memory.
Dynamic memory allocation enables C programmers to allocate memory at runtime.
The different functions we use to dynamically allocate memory at runtime include:
The following C program is used to display elements and calculate the sum of n numbers.
Using dynamic memory allocation functions, we try to reduce the waste of memory.
Demonstration
#include<stdio.h> #include<stdlib.h> void main(){ //Declaring variables and pointers,sum// int numofe,i,sum=0; int *p; //Reading number of elements from user// printf("Enter the number of elements : "); scanf("%d",&numofe); //Calling malloc() function// p=(int *)malloc(numofe*sizeof(int)); /*Printing O/p - We have to use if statement because we have to check if memory has been successfully allocated/reserved or not*/ if (p==NULL){ printf("Memory not available"); exit(0); } //Printing elements// printf("Enter the elements : </p><p>"); for(i=0;i<numofe;i++){ scanf("%d",p+i); sum=sum+*(p+i); } printf("</p><p>The sum of elements is %d",sum); free(p);//Erase first 2 memory locations// printf("</p><p>Displaying the cleared out memory location : </p><p>"); for(i=0;i<numofe;i++){ printf("%d</p><p>",p[i]);//Garbage values will be displayed// } }
Enter the number of elements : 5 Enter the elements : 23 34 12 34 56 The sum of elements is 159 Displaying the cleared out memory location : 12522624 0 12517712 0 56
The above is the detailed content of Explain dynamic memory allocation in C language with an example. For more information, please follow other related articles on the PHP Chinese website!