C Reference function calloc()

The function calloc() will allocate a block of memory for an array. All of these elements are size bytes long. During the initialization all bits are set to zero.

Usage of calloc():

void * calloc ( size_t num, size_t size );

Parameters:

Number of elements (array) to allocate and the size of elements.

Return value:


Will return a pointer to the memory block. If the request fails, a NULL pointer is returned.

Source code example of calloc():


	#include<stdio.h>
	#include<stdlib.h>

	int main ()
	{
		int a,n;
		int * ptr_data;

		printf ("Enter amount: ");
		scanf ("%d",&a);

		ptr_data = (int*) calloc ( a,sizeof(int) );
		if (ptr_data==NULL)
		{
			printf ("Error allocating requested memory");
			exit (1);
		}

		for ( n=0; n<a; n++ )
		{
			printf ("Enter number #%d: ",n);
			scanf ("%d",&ptr_data[n]);
		}

		printf ("Output: ");
		for ( n=0; n<a; n++ )
			printf ("%d ",ptr_data[n]);

		free (ptr_data);
		return 0;
	}

This entry was posted in C Reference stdlib.h Functions. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

There are currently 8 responses to “C Reference function calloc()”

Why not let us know what you think by adding your own comment!

  1. anchre on May 23rd, 2011:

    :)……thx was really helpfull…

  2. Sanjib Das on June 16th, 2011:

    Nice Statement.

  3. Puneet Rana on August 11th, 2011:

    really nyc description ,very brief nd helpful too thx alot .

  4. A.Vivek on March 7th, 2012:

    Friends,

    I have question. What is the difference between calloc(2, sizeof(char)) and calloc(1, sizeof(short))

  5. puja kumari on April 3rd, 2012:

    way of explaining is quite appreciable.i like it.

  6. jamshed on May 4th, 2012:

    excellent

  7. will on June 7th, 2013:

    A.Vivek,

    In practice, not that much, but whats going on are two things: first is a portability issue; char is pretty universally one byte and short is 2, but who knows, maybe somewhere they’re a different size (this is more of an issue with floats/longs and even ints some places). The second is what you’re storing there and how you want to access it; with C, there’s a workaround for everything – rules are meant to be broken – but if you want two 1-byte elements, do it the first way, if you want 1 2-byte element, do it the second.

  8. Abhishek on July 8th, 2013:

    thanx. It was vry helpfull