/* Introduction
to program:
Program
- dynavg.c.
Example
of dynamic memory allocation.
Based
on P93.c from Paul Kelly's "A guide to C programming".
Francis
O'Donovan 21-1-98. */
/* Files to be included. */
#include <stdio.h>
#include <stdlib.h>
/* Function: main(). */
main()
{
/*
Initialize variables. */
int *int_array;
/* Pointer to array. */
int
no_els, no_bytes, i;/* The number of elements, bytes and a counter.
*/
int
average;
/* The average of the numbers. */
/* Print introduction on screen. */
printf( "Program: dynavg.c.\n" );
printf(
"Example of dynamic memory allocation.\n" );
printf(
"Based on P93.c from Paul Kelly\'s \"A guide to C programming\".\n"
);
printf(
"Francis O'Donovan 21-1-98.\n\n" );
/* Ask user how many numbers will be inputted. */
printf( "Please type in the number of integers whose average
is to be calculated.\n" );
scanf(
"%d", &no_els );
/* Calculate the number of bytes required by array for the numbers inputted. */
no_bytes = no_els * sizeof(int);
/* Try to allocate memory, and return error if fail. */
int_array = malloc (no_bytes);
if ( int_array == NULL )
{
printf( "Cannot allocate memory for array!!!!\n" );
printf( "Program terminated. Goodbye!\n" );
}
else
{
/* Enter elements into array. */
/* As the numbers are entered, add them together. */
average = 0;
printf( "Please type integers only.\n" );
for ( i = 0; i < no_els; i++ )
{
printf( "\nEnter number %d: ", i+1 );
scanf( "%d", int_array+i );
average += *(int_array+i);
}
/* Calculate average of numbers by dividing average by no_els. */
average /= no_els;
/* Output average and free memory. */
printf( "The average (int form) is %d.\n", average );
free ( int_array );
}
}
© Francis O'Donovan
1999.