calloc() Function :
The calloc function is used to allocate storage to a variable while the program is running. This library function is invoked by writing calloc(num,size).This function takes two arguments that specify the number of elements to be reserved, and the size of each element in bytes and it allocates memory block equivalent to num * size . The function returns a pointer to the beginning of the allocated storage area in memory. The important difference between malloc and calloc function is that calloc initializes all bytes in the allocation block to zero and the allocated memory may/may not be contiguous.
calloc function is used to reserve space for dynamic arrays. Has the following form.
void * calloc (size_t n, size_t size);
Number of elements in the first argument specifies the size in bytes of one element to the second argument. A successful partitioning, that address is returned, NULL is returned on failure.
For example, an int array of 10 elements can be allocated as follows.
int * array = (int *) calloc (10, sizeof (int));
Note that this function can also malloc, written as follows.
int * array = (int *) malloc (sizeof (int) * 10);
However, the malloc function, whereas the area reserved to the states that are undefined, the area allocated by the calloc function contains a 0. In fact, the calloc function is internally may be a function that calls malloc. After securing function by malloc, the area is filled with 0.
ptr = malloc(10 * sizeof(int)); is just like this:
ptr = calloc(10, sizeof(int));
C – CALLOC FUNCTION EXAMPLE PROGRAM :
int *i,*j*ptr = calloc(5,sizeof(int));
if(ptr == NULL)
printf(“!We are probably out of memory !\n”);
printf(“Default values are :\n”);
for (i=ptr,j=0; j<5; i++,j++)
printf(“New values : \n”);
printf(“i=%d\t*i=%d \n ”,i,*i);
|Default values are:
i = 1526 *i=0
i = 1528 *i=0
i = 1530 *i=0
i = 1532 *i=0
i = 1534 *i=0
New values :
i = 1526 *i=1
i = 1528 *i=2
i = 1530 *i=3
i = 1532 *i=4
i = 1534 *i=5