calloc | function |
void * calloc ( size_t num, size_t size ); |
<cstdlib> |
Allocate space for array in memory
Allocates a block of memory for an array of num elements, each of them size bytes long, and initializes all its bits to zero.
The effective result is the allocation of an zero-initialized memory block of (num * size) bytes.
Parameters
- num
- Number of elements to be allocated.
- size
- Size of elements.
Return Value
A pointer to the memory block allocated by the function.The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
If the function failed to allocate the requested block of memory, a NULL pointer is returned.
Example
/* calloc example */ #include <stdio.h> #include <stdlib.h> int main () { int i,n; int * pData; printf ("Amount of numbers to be entered: "); scanf ("%d",&i); pData = (int*) calloc (i,sizeof(int)); if (pData==NULL) exit (1); for (n=0;n<i;n++) { printf ("Enter number #%d: ",n); scanf ("%d",&pData[n]); } printf ("You have entered: "); for (n=0;n<i;n++) printf ("%d ",pData[n]); free (pData); return 0; } |
This program simply stores numbers and then prints them out. But the number of items it stores can be adapted each time the program is executed because it allocates as much dynamic memory as needed during runtime.
See also
free | Deallocate space in memory (function) |
malloc | Allocate memory block (function) |
realloc | Reallocate memory block (function) |