Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to calculate sum of elements of array using malloc function

C Code Example — Structure Programs

ADVERTISEMENT

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

  1. Include stdlib.h for dynamic memory functions.
  2. Read n elements.
  3. Allocate memory using ptr = (int*) malloc(n * sizeof(int)).
  4. Check if ptr == NULL to ensure allocation succeeded.
  5. Loop n times: read input into ptr+i and add *(ptr+i) to the sum.
  6. 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 NULL because if the computer runs out of RAM, malloc will fail. Finally, every time you use malloc, you MUST use free() at the end of your program to prevent memory leaks.

Complexity

Time Complexity O(n)
Space Complexity O(n)
ADVERTISEMENT