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()



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

What's the point of const pointers?

const is a tool which you should use in pursuit of a very important C++ concept:

Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean.

Even though it does not change the functionality, adding const generates a compiler error when you're doing things you didn't mean to do. Imagine the following typo:

void foo(int* ptr)
{
    ptr = 0;// oops, I meant *ptr = 0
}

If you use int* const, this would generate a compiler error because you're changing the value to ptr. Adding restrictions via syntax is a good thing in general. Just don't take it too far -- the example you gave is a case where most people don't bother using const.

Ref : https://bit.ly/33Cdn3Q