/* File: memory.c Description: Uses malloc to dynamically create an array of n ints. The user enters n. The program allocates the memory, fills it with random integers scaled between 18 and -9, displays the array and frees the memory. It does this forever Input: User enters size of the array. Output: Displays the contents of the full array and sums up all the elements. This problem is adapted from A Book on C (Kelly, Pohl) pg. 261. */ #include #include #include #include // local header file for memory with various useful macros. // We use MALLOC_CHECK(), BZERO(), MY_ASSERT(), LOG() #include "header.h" // prototypes void initArray(int *, int ); int sumArray(int *, int ); void displayArray(int *, int ); int main (void) { int *ip, n; srand(time(NULL)); printf("\n%s\n", "This program does the following repeatedly:\n" "\n" " 1) Create space for an array of size n\n" " 2) Fill the array with randomly distributed digits\n" " 3) Prints the array and the sum of its elements\n" " 4) Frees the allocated memory\n"); for ( ; ; ) { // do forever printf("Input the size of array you want created. n: "); if (scanf("%d", &n) !=1 || n < 1) { LOG("Usage: n has to be > 0\n\n"); continue; // try again } // User enters size of array. We dynamically allocate memory using the // MALLOC_CHECK and display the array. Note, that malloc() allocate // unused space for an object whose size in bytes is specified by n // and whose value is unspecified. Because of that it is a good idea //to zeroise the returned memory. putchar('\n'); // allocate memory - n bytes; that is n*sizeof(int) bytes ip = malloc(n*sizeof(int)); MALLOC_CHECK(ip); // display malloc'd array, recall memory not specified could be any value displayArray(ip, n); // display BZERO'd array BZERO(ip, n*sizeof(int)); displayArray(ip, n); // display initialed array and sum initArray(ip, n); displayArray(ip, n); printf("Sum = %d\n\n", sumArray(ip, n)); // don't forget to free the memory or we will have memory leaks free(ip); } printf("\nLater!\n\n"); return 0; } void initArray(int *a, int n) { int i; for (i = 0; i < n; i++) a[i] = rand()%19 - 9; // scales between 18 and - 9 } int sumArray(int *a, int n) { int i, sum =0; for (i = 0; i < n; i++) sum += a[i]; return(sum); } void displayArray(int *a, int n) { int i; printf("a = ["); for (i = 0; i < n; i++) printf("%d%s", a[i], ((i < n - 1) ? ", " : "]\n")); }