/* Implementation of the simple 'array' ADT, plus a short main program for testing. */ #include "anx15-02.h" #include #include /**** array_create **** On entry: size is the number of elements needed in the array. On exit: returns a pointer to an array, or NULL. */ ARRAY * array_create(int size) { ARRAY * A; A = (ARRAY*) malloc(sizeof(ARRAY)); if (A == NULL) { return NULL; /* failure */ } A->elements = (float*)malloc(size * sizeof(float)); /* Allocate elements */ if (A->elements == NULL) { free(A); return NULL; } A->size = size; return A; } /**** array_free **** On entry: arr is a pointer to an array. On exit: The array has been freed. */ void array_free(ARRAY * arr) { free(arr->elements); /* MUST free in this order! (Do you see why?) */ free(arr); } /* static */ void check_bounds (ARRAY * a, int n); /**** array **** On entry: arr is an ARRAY, n is the index of the required element. On exit: Returns the value of the selected element. */ float array(ARRAY * arr, int n) { check_bounds(arr, n); return arr->elements[n]; } /**** array_set **** On entry: arr is an ARRAY, n is the index of an element. On exit: Element n of arr has been assigned the value f. */ void array_set(ARRAY * arr, int n, float f) { check_bounds(arr, n); arr->elements[n] = f; } /* check-bounds: Does nothing if the index is within the array, else prints an informative message, and terminates the program. Note: If you have read section 18.3, this function should be static. */ /* static */ void check_bounds (ARRAY * a, int n) { if (n < 0 || n >= a->size) { fprintf( stderr, "ERROR: Request for element %d in a %d-element array\n", n, a->size ); exit(1); } } /************************************************************************ Test main program. Allocates a 10-element array, fills each element with its own index+.5, then tries to print 11 elements. Should end with an error! */ main () { ARRAY * ap; int i; ap = array_create(10); if (ap == NULL) { fprintf(stderr, "Cannot allocate the array.\n"); exit(1); } printf("Setting the array elements:\n"); for (i=0; i<10; i++) { array_set(ap, i, i + 0.5); printf("ap[%d] set to %f\n", i, i + 0.5); } printf( "Checking the elements; we try to check element 11, so we\n" "should end with an error message.\n" ); for (i=0; i<11; i++) { array_set(ap, i, i + 0.5); printf("ap[%d] is %f\n", i, array(ap,i)); } printf("You should never read this!!\n"); exit(0); }