C Program to calculate sum of elements of array using malloc function
Objective
Write a C program to calculate the sum of elements of an array using the malloc function.
Algorithm / Approach
- Include
stdlib.hfor dynamic memory functions. - Read
nelements. - Allocate memory using
ptr = (int*) malloc(n * sizeof(int)). - Check if
ptr == NULLto ensure allocation succeeded. - Loop
ntimes: read input intoptr+iand add*(ptr+i)to the sum. - Print the sum and release the memory using
free(ptr).
main.c
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter Number of Elements : ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int));
if(ptr==NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter Elements of array : ");
for(i=0; i < n; ++i) {
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum = %d",sum);
free(ptr);
return 0;
}
Expected Output
Enter Number of Elements : 2 Enter Elements of array : 2 4 Sum = 6
Explanation of the Program
malloc()(Memory Allocation) reserves a single large block of contiguous memory.- It is crucial to check if the pointer is
NULLbecause if the computer runs out of RAM,mallocwill fail. Finally, every time you usemalloc, you MUST usefree()at the end of your program to prevent memory leaks.
Complexity
Time Complexity
O(n)
Space Complexity
O(n)