calloc()
The function of calloc() function is exactly same as that of malloc() function. That is it helps us to allocate block of memory dynamically.
Syntax:
datatype *pointervariable;
pointervariable=(cast type)calloc(n,s);
n: total number of memory locations
s: size of one element
To allocate memory dynamically for storing 10 integers
int *p;
P=(int*)calloc(10,sizeof(int));
P=(int*)calloc(10,2);
To allocate memory dynamically for storing 10 characters
char *p;
P=(char*)calloc(10,sizeof(char));
P=(char*)calloc(10,1);
In general to allocate memory dynamically for n integers
Before using the memory block which has been allocated dynamically it is very important to verify whether the memory has been successfully allocated or not. If memory is successfully allocated then the base address of the allocated memory block is returned back and stored in the pointer variable. On the other hand, if memory allocation fails then NULL is returned back and stored in the pointer variable.
int n,*p;
printf(“Enter total elements “);
scanf(“%d”,&n);
p=(int*)calloc(n,sizeof(int));
if (p==NULL)
{
printf (“memory allocation failed”);
return;
}
Difference between malloc() and calloc() function.
1.
While allocating memory using malloc() function we are required to specify one argument whereas while allocating memory with calloc() function we are required to specify two arguments.
p= (int*) malloc(n*sizeof(int));
P=(int*)calloc(n,sizeof(int));
2.
The memory allocated with the help of malloc() function by default contains garbage whereas the memory block allocated with the help of calloc() function by default initialized by zero.