Calloc() function (Contiguous Memory Allocation Function):
- calloc() function is another memory allocation function used for dynamic memory allocation for storing derived data types such as arrays and structures etc.,
- malloc() function allocates a single block of storage space, whereas calloc() function allocates multiple blocks of storage space with each of same size and all locations are initialized with ‘0’. The general form of calloc() function is:
Syntax: ptrvariable =
(casttype*)calloc(n,elesize);
Where,
ptrvariable is a pointer variable of type casttype.
n represents number of blocks.
elesize represents block size.
All blocks are initialized with ‘0’ and a pointer of the
first block is returned. If there is not
enough space to allocate, then it returns a NULL pointer.
Example: int *X;
X = (int*)calloc(5,sizeof(int));
For this, memory allocation
will be:
/*
EXAMPLE PROGRAM FOR CALLOC() FUNCTION */
main()
{
int *p,i,n;
clrscr();
printf("\nEnter how many
numbers:");
scanf("%d",&n);
p=(int*)calloc(n,sizeof(int));
printf("\nEnter %d
Elements:",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("\nArray Elements
Are:");
for(i=0;i<n;i++)
printf(" %d",*(p+i));
}
No comments:
Post a Comment