The malloc is an acronym of "memory allocation". This function allocates the requested size of bytes to a variable and return a pointer of type void.
Syntax:
p=(type cast *)malloc(size)
Here p is a pointer.
Example:
Calculate the sum to element using malloc()
#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,*p,total=0;
printf("Enter number of elements: ");
scanf("%d",&n);
p=(int*)malloc(n*sizeof(int)); //memory allocated
if(p==NULL)
{
printf("No Space available");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",p+i);
total+=*(p+i);
}
printf("Sum of elements=%d",total);
free(p); // used to release space
return 0;
}
0 Comment(s)