w3resource

C calloc() function

C calloc() function - A memory allocator

The calloc() function is used to reserve storage space for an array of num elements, each of length size bytes. The function then gives all the bits of each element an initial value of 0.

Syntax:

void *calloc(size_t nitems, size_t size)

Parameters:

Name Description Required /Optional
nitems Number of elements. Required
size Length in bytes of each element. Required

Return value from calloc()

  • Returns a pointer to the reserved space.
  • The return value is NULL if there is not enough storage, or if num or size is 0.

Example: calloc() function

The following example shows the usage of calloc() function.


#include <stdio.h>
#include <malloc.h>

int main( void )
{
   long *buffer;

   buffer = NULL;
   if( buffer != NULL )
      printf( "Allocated 15 long integers.\n" );
   else
      printf( "Can't allocate memory.\n" );
   
   buffer = (long *)calloc( 15, sizeof( long ) );
   if( buffer != NULL )
      printf( "\nAllocated 15 long integers.\n" );
   else
      printf( "\nCan't allocate memory.\n" );
   free( buffer );
}

Output:

Can't allocate memory.

Allocated 15 long integers.

C Programming Code Editor:

Previous C Programming: C strtoul()
Next C Programming: C free()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/c-programming/stdlib/c-calloc.php