Allocates an array in memory and initializes the elements to 0.
Include
<stdlib.h>
Prototype
void *calloc(size_t nelem, size_t size);
Arguments
nelem
|
number of elements |
size
|
length of each element |
Return Value
Returns a pointer to the allocated space if successful; otherwise, returns a null pointer.
Remarks
Memory returned by calloc
is aligned correctly for any size data element
and is initialized to zero. This function requires a heap.
Example
/* This program allocates memory for the */
/* array 'i' of long integers and initializes */
/* them to zero. */
#include <stdio.h> /* for printf, NULL */
#include <stdlib.h> /* for calloc, free */
int main(void)
{
int x;
long *i;
i = (long *)calloc(5, sizeof(long));
if (i != NULL)
{
for (x = 0; x < 5; x++)
printf("i[%d] = %ld\n", x, i[x]);
free(i);
}
else
printf("Cannot allocate memory\n");
}
Example Output
i[0] = 0
i[1] = 0
i[2] = 0
i[3] = 0
i[4] = 0