Monday 16 September 2013

Monday 16 September 2013

Dynamic memory allocation




Allocate a dynamic array of a stated size.Load numbers into the array and then sum the numbers in the array.

#include <stdio.h>

#include <stdlib.h>


int main()
{
int retval;   /* value returned from scanf */
long *nums;   /* pointer to arrray of numbers to sum */
short how_many;/* number of numbers to input and sum */
short inum;   /* counter to index into nums array */
long sum;     /* sum of numbers in nums array */
    /*
    *    input number of elements to allocate
    */
    printf("\nHow many numbers to sum? ");
    scanf("%hd",&how_many);
    /*
    *    dynamically allocate memory for how_manay 
    *    long's
    */
 nums = (long *)calloc(how_many, sizeof(long) );

    if(nums == (long *)NULL)
    {
         fprintf(stderr,"\nCould not allocate memory");
         return 1;
    }
    /*
    *    input numbers to store in array
    */
    for( inum =0; inum < how_many; ++inum)
    {
         printf("\nEnter #%d: ", inum + 1);
         retval = scanf("%ld",&nums[inum] );
    }
    /*
    *    sum the numbers in the array
    */
    for( sum = inum = 0; inum < how_many; ++inum )
    {
         /*
         *    add number to sum
         */
         sum += nums[inum];
         /*
         *    show running total
         */
         printf("\n%3d: %10ld %10ld",
              inum+1,nums[inum],sum);
    }
    /*
    *    print the final total
    */
    printf("\nThe sum of the %d numbers",how_many);
    printf(" entered is %ld\n",sum);
    /*
    *    free the memory back to the heap
    */
    free( (char *)nums );
    return 0;

}

Executing the program....
$demo
How many numbers to sum? 
Enter #1: 
Enter #2: 
  1:         21         21
  2:          3         24
The sum of the 2 numbers entered is 24

No comments:

Post a Comment