cplusplus.com cplusplus.com
cplusplus.com   C++ : Reference : C Library : cstdlib (stdlib.h) : calloc
 
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forum
Reference
C Library
IOstream Library
Strings library
STL Containers
STL Algorithms
C Library
cassert (assert.h)
cctype (ctype.h)
cerrno (errno.h)
cfloat (float.h)
climits (limits.h)
clocale (locale.h)
cmath (math.h)
csetjmp (setjmp.h)
csignal (signal.h)
cstdarg (stdarg.h)
cstddef (stddef.h)
cstdio (stdio.h)
cstdlib (stdlib.h)
cstring (string.h)
ctime (time.h)
cstdlib (stdlib.h)
functions:
· abort
· abs
· atexit
· atof
· atoi
· atol
· bsearch
· calloc
· div
· exit
· free
· getenv
· labs
· ldiv
· malloc
· mblen
· mbstowcs
· mbtowc
· qsort
· rand
· realloc
· srand
· strtod
· strtol
· strtoul
· system
· wcstombs
· wctomb
functions (non-standard):
· itoa
macros:
· EXIT_FAILURE
· EXIT_SUCCESS
· MB_CUR_MAX
· NULL
· RAND_MAX
types:
· div_t
· ldiv_t
· size_t

-

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)
© The C++ Resources Network, 2000-2007 - All rights reserved
Spotted an error? - contact us