Problem
How to display and calculate the sum of n numbers by using dynamic memory allocation function in C language?
Solution
Following is the C program to display the elements and calculate the sum of n numbers by the user by using dynamic memory allocation functions. Here, we also try to reduce the wastage of memory.
Example
#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 : \n"); for(i=0;i<numofe;i++){ scanf("%d",p+i); sum=sum+*(p+i); } printf("\nThe sum of elements is %d",sum); free(p);//Erase first 2 memory locations// printf("\nDisplaying the cleared out memory location : \n"); for(i=0;i<numofe;i++){ printf("%d\n",p[i]);//Garbage values will be displayed// } }
Output
When the above program is executed, it produces the following result −
Enter the number of elements: 4 Enter the elements: 23 45 67 89 The sum of elements is 224 Displaying the cleared out memory location: 7410816 0 7405904 0