Latest web development tutorials

C library functions - calloc ()

C standard library - <stdlib.h> C standard library - <stdlib.h>

description

C library functionsvoid * calloc (size_t nitems, size_t size) allocate the required memory space and returns a pointer to it.Different points between themalloc and calloc,malloc memory is not set to zero, while calloc sets allocated memory to zero.

statement

Here is () statement calloc function.

void *calloc(size_t nitems, size_t size)

parameter

  • nitems - the number of elements to be allocated.
  • size - the size of the element.

return value

This function returns a pointer to the allocated memory. If the request fails, it returns NULL.

Examples

The following example demonstrates the calloc () function is used.

#include <stdio.h>
#include <stdlib.h>

int main()
{
   int i, n;
   int *a;

   printf("要输入的元素个数:");
   scanf("%d",&n);

   a = (int*)calloc(n, sizeof(int));
   printf("输入 %d 个数字:\n",n);
   for( i=0 ; i < n ; i++ ) 
   {
      scanf("%d",&a[i]);
   }

   printf("输入的数字为:");
   for( i=0 ; i < n ; i++ ) {
      printf("%d ",a[i]);
   }
   
   return(0);
}

Let's compile and run the above program, which will result in the following:

要输入的元素个数:3
输入 3 个数字:
22
55
14
输入的数字为:22 55 14

C standard library - <stdlib.h> C standard library - <stdlib.h>