malloc() function in C

malloc() function in C

  • The malloc() function allocates single block of requested memory.
  • It doesn't initialize memory at execution time, so it has garbage value initially.
  • It returns NULL if memory is not sufficient.
  • The syntax of malloc() function is given below:
ptr=(cast-type*)malloc(byte-size) 
https://mskuthar.blogspot.com/
malloc in C

Example of malloc() function.
#include <stdio.h>  
#include <stdlib.h>  
void main(){  
    int n,i,*ptr,sum=0;  
    printf("Enter number of elements: ");  
    scanf("%d",&n);  
    ptr=(int*)malloc(n*sizeof(int));  //memory allocated using calloc  
    if(ptr==NULL)                       
    {  
        printf("Sorry! unable to allocate memory");  
        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);  
}  
Output will be

Enter elements of array: 3
Enter elements of array: 10
10
10

Sum=30

Post a Comment

Previous Post Next Post