/* File: allocate3.c This file demonstrates memory allocation, where the size of the array grows. */ #define STARTING_SIZE 10 #define SENTINNEL -1 #include #include "genlib.h" #include "simpio.h" #include main() { int i, j, size, n, array_size, *A, *New, *temp; /* get a block of memory for size integer */ A = malloc( STARTING_SIZE * sizeof(int) ) ; if (A == NULL) { Error("Oops, we're out of memory\n") ; } array_size = STARTING_SIZE ; printf("Enter the elements of the integer array.\n") ; printf("Use -1 to indicate the end of the array.\n") ; /* Read in the integer array */ i = 0 ; while(TRUE) { n = GetInteger() ; if (n == SENTINNEL) break ; /* Check if we have enough space */ if (i == array_size) { array_size = 2 * array_size ; New = malloc(array_size * sizeof(int)) ; if (New == NULL) Error("Memory capacity exceeded\n") ; /* Copy old array into new array */ for (j = 0 ; j < i ; j++) { New[j] = A[j] ; } /* Make A point to new array, free old array */ temp = A ; A = New ; free(temp) ; } A[i] = n ; i++ ; } size = i ; /* Print out contents of the array */ printf("\nThe integers in array A\n") ; for (i = 0 ; i < size ; i++) { printf("A[%d] = %d\n", i, A[i]) ; } /* Give up use of the memory block */ free(A) ; }