calloc() function in C

Previous
Next

Calloc():

  • It is used to allocate memory to arrays dynamically.
  • It is belongs to stdlib.h header file.
  • The prototype is:

void*  calloc(size_t  n, size_t size);

After memory allocation, all the locations initializes with default values.

Note: When a pointer is pointing to array, we access elements using addresses not through indexing. Generally we use arr[i] as *(arr+i)

#include<stdio.h>
#include<stdlib.h>
int main()
{
	int *arr, n, i;
	printf("Enter array size : ");
	scanf("%d", &n);
	arr = (int*)calloc(n, sizeof(int));
	if(arr==NULL)
	{
		printf("Out of memory \n");
	}
	else
	{
		printf("Array default values are : \n");
		for(i=0 ; i<n ; i++)
		{
			printf("%d \n", *(arr+i));
		}
	}
	return 0;	
}

Reading elements into array and find the sum of all elements in array:

#include<stdio.h>
#include<stdlib.h>
int main()
{
	int *arr, n, i, sum=0;
	printf("Enter array size : ");
	scanf("%d", &n);
	arr = (int*)calloc(n, sizeof(int));
	if(arr==NULL)
	{
		printf("Out of memory \n");
	}
	else
	{
		printf("Enter %d elements : \n", n);
		for(i=0 ; i<n ; i++)
		{
			scanf("%d", arr+i);
		}
		for(i=0 ; i<n ; i++)
		{
			sum = sum + *(arr+i);
		}
		printf("Sum of array elements : %d \n", sum);
	}
	return 0;	
}
Previous
Next

Add Comment

Courses Enquiry Form