C – Calloc() Function

calloc() : Allocate memory to Arrays using pointers.

                        void* calloc(size_t n , size_t size);

  • First argument specifies number of elements in the array.
  • Second argument specifies size of each element.
  • If memory is available, it allocates n*size bytes and returns first byte address.
  • If no memory, it returns NULL.
  • After allocating the memory all the byte locations are initialized with “0” by default.
#include<stdio.h>
#include<stdlib.h>
int main()
{
            int n, *arr, i;
           
            printf(“Enter size of array : “);
            scanf(“%d”, &n);
           
            arr = (int*)calloc(n, sizeof(int));
            if(arr==NULL){
                        printf(“Failed in memory allocation \n”);
            }
            else{
                        printf(“Array elements are :  \n”);
                        for(i=0 ; i<n ; i++)
                        {
                                    printf(“%d \n”, *(arr+i));
                        }
            }
            return 0;
}

Read and find the sum of array elements:

#include<stdio.h>
#include<stdlib.h>
int main()
{
            int n, *arr, i, sum=0;
           
            printf(“Enter size of array : “);
            scanf(“%d”, &n);
           
            arr = (int*)calloc(n, sizeof(int));
            if(arr==NULL){
                        printf(“Failed in memory allocation \n”);
            }
            else{
                        printf(“Enter array elements :  \n”);
                        for(i=0 ; i<n ; i++)
                                    scanf(“%d”, arr+i);
                        for(i=0 ; i<n ; i++)
                                    sum = sum + *(arr+i);
                       
                        printf(“Sum is : %d \n”, sum);
            }
            return 0;
}
Scroll to Top