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! or use
to share this post with others.
:)……thx was really helpfull…
Nice Statement.
really nyc description ,very brief nd helpful too thx alot .
Friends,
I have question. What is the difference between calloc(2, sizeof(char)) and calloc(1, sizeof(short))
way of explaining is quite appreciable.i like it.
excellent
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.
thanx. It was vry helpfull