C library memory allocation function void *calloc(size_t nitems, size_t size) allocates the requested memory and returns a pointer to it.
The difference between malloc and calloc is that malloc does not set the memory to zero, while calloc sets the allocated memory to zero.
Memory can be allocated in two ways, as described below-
After memory is allocated at compile time, during execution Unchangeable. There will be problems of insufficient or wasted memory.
The solution is to dynamically create memory, that is, create memory according to user requirements during program execution.
The standard library functions for dynamic memory management are as follows: -
This function is used to allocate contiguous memory blocks at runtime.
This is specially designed for arrays.
It returns a void pointer that points to the base address of the allocated memory.
The syntax of the calloc() function is as follows -
void *calloc ( numbers of elements, size in bytes)
The following example shows the usage of the calloc() function.
int *ptr; ptr = (int * ) calloc (500,2);
Here, 500 memory blocks of size 2 bytes will be allocated continuously. Total memory allocated = 1000 bytes.
< /p>
int *ptr; ptr = (int * ) calloc (n, sizeof (int));
Given below is a C program that uses the dynamic memory allocation function Calloc to calculate the sum of even and odd numbers in a set of elements.
Online Demonstration
#include<stdio.h> #include<stdlib.h> void main(){ //Declaring variables, pointers// int i,n; int *p; int even=0,odd=0; //Declaring base address p using Calloc// p = (int * ) calloc (n, sizeof (int)); //Reading number of elements// printf("Enter the number of elements : "); scanf("%d",&n); /*Printing O/p - We have to use if statement because we have to check if memory has been successfully allocated/reserved or not*/ if (p==NULL){ printf("Memory not available"); exit(0); } //Storing elements into location using for loop// printf("The elements are : </p><p>"); for(i=0;i<n;i++){ scanf("%d",p+i); } for(i=0;i<n;i++){ if(*(p+i)%2==0){ even=even+*(p+i); } else { odd=odd+*(p+i); } } printf("The sum of even numbers is : %d</p><p>",even); printf("The sum of odd numbers is : %d</p><p>",odd); }
When the above program is executed, the following results will be produced -
Enter the number of elements : 4 The elements are : 12 56 23 10 The sum of even numbers is : 78 The sum of odd numbers is : 23
The above is the detailed content of What is Calloc in C language?. For more information, please follow other related articles on the PHP Chinese website!