C - calloc
Structure and Linked List with C Programming in Tamil

Learn C - C tutorial - calloc - C examples - C programs
C - calloc() Function - Definition and Usage
- Calloc () function is similar to malloc function.
- But in Calloc function the memory space will be initialized before the memory allocation is set as zero.

C Syntax
calloc (number, sizeof(int));
or
ptr=(cast-type*)calloc(number, byte-size)

Example 1
Sample - C Code
#include <stdio.h>
#include <conio.h>
void main()
{
char *var_memoryalloc;
clrscr();
/* memory is allocated dynamically */
var_memoryalloc = calloc( 20 * sizeof(char) );
if( var_memoryalloc== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( var_memoryalloc,"wikitechy.com");
}
printf("Dynamically allocated memory content : " \
"%s\n", var_memoryalloc );
free(var_memoryalloc);
getch();
}
C Code - Explanation

- In this statement we declare the pointer variable *ptr as integer and we assign the value for the variable “q=20” .
- In this statement we assign the address of the “q” variable to “ptr” .
- In this printf statement we print the address of the variable “q” .
- In this printf statement we print the value of the variable “q” .
Sample Output - Programming Examples

- Here in this output the dynamic memory will be allocated and the string “wikitechy.com” will be copied and printed as shown in the console window.
Example 2
Sample Code
#include<stdio.h>
#include<stdlib.h>
void main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array:");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
getch();
}

Output
Enter number of elements :3
Enter elements of array:10
10
10
sum=30