Note that like malloc(), calloc() returns a pointer value, but with the added feature that the memory is initialized to zero. The parameters for calloc() are different than for malloc()
Also, when we are done with the block of memory allocated by calloc() we should free it using the function free().
/******************** ** File: calloc.c ** Author: D. Frey ** Date: 1/25/00 ** Section 0101 ** E-Mail: frey@cs.umbc.edu ** Modified by: Sue Evans ** Modification date: 9/25/05 ** ** This program demonstrates the use of calloc() ** to dynamically allocate memory ********************/ #include <stdio.h> #include <stdlib.h> int main () { int *values; int total = 0; int i; int nrInputs; /* ask user for how many ints */ printf ("Enter number of integers: "); scanf ("%d", &nrInputs); /* allocate memory required */ values = (int *)calloc(nrInputs, sizeof(int)); if (values == NULL) { printf ("Oops, out of memory\n"); exit(-1); } /* input the numbers into the array */ for (i = 0; i < nrInputs; i++) { printf ("Input an integer: "); scanf ("%d", &values[i]); } /* sum all elements of the array */ for (i = 0; i < nrInputs; i++) { total += values[i]; } free (values); /* print the total */ printf ("\nThe total is : %d\n", total); return 0; }