C - calloc



Structure and Linked List with C Programming in Tamil


 calloc

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 calloc Function

C Syntax

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

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

code-explanation-calloc
  1. In this statement we declare the pointer variable *ptr as integer and we assign the value for the variable “q=20” .
  2. In this statement we assign the address of the “q” variable to “ptr” .
  3. In this printf statement we print the address of the variable “q” .
  4. In this printf statement we print the value of the variable “q” .

Sample Output - Programming Examples

code-explanation-calloc-output
  1. 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();
}

calloc c programming

Output

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

View More Quick Examples


Related Searches to c calloc function