UMBC CS 201, Spring 02
Allocating memory with calloc()
This program uses calloc() to allocate an array
of integers.
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().
The Program
/********************
** File: calloc.c
** Author: D. Frey
** Date: 1/25/00
** Section 0101
** SSN: 123-45-6789
** E-Mail: frey@cs.umbc.edu
**
** This program demonstrates the use of calloc()
** to dynamically allocate memory
********************/
#include
#include
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;
}
The Sample Run
linux1[86] % gcc -Wall -ansi calloc.c
linux1[87] % a.out
Enter number of integers: 10
Input an integer: 5
Input an integer: -2
Input an integer: 8
Input an integer: 34
Input an integer: 200
Input an integer: 12
Input an integer: -60
Input an integer: 14
Input an integer: 7
Input an integer: 93
The total is : 311
linux1[88] %
CSEE
|
201
|
201 S'02
|
lectures
|
news
|
help
Last Modified - Tuesday, 02-Apr-2002 16:06:24 EST