Name
calloc
Synopsis
Allocates memory for an array
#include <stdlib.h> void *calloc
( size_tn
, size_tsize
);
The calloc()
function
obtains a block of memory from the operating system that is large
enough to hold an array of n
elements of
size size
.
If successful, calloc()
returns a void
pointer to the
beginning of the memory block obtained. void
pointers are converted automatically
to another pointer on assignment, so that you do not need to use an
explicit cast, although you may want do so for the sake of clarity.
If no memory block of the requested size is available, the function
returns a null pointer. Unlike malloc()
, calloc()
initializes every byte of the
block allocated with the value 0.
Example
size_t n;
int *p;
printf("\nHow many integers do you want to enter? ");
scanf("%u", &n);
p = (int *)calloc
(n, sizeof(int)); /* Allocate some memory */
if (p == NULL)
printf("\nInsufficient memory.");
else
/* read integers into array elements ... */
Get C in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.