C – Calloc 2017-08-07T14:19:00+00:00

calloc() Function :

This 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.  calloc initializes all bytes in the allocation block to zero and the allocated memory may/may not be contiguous.

This 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.


Output :

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

Prev Next