home *** CD-ROM | disk | FTP | other *** search
/ World of Shareware - Software Farm 2 / wosw_2.zip / wosw_2 / CPROG / CGAZV5N3.ZIP / ARRAY.C < prev    next >
C/C++ Source or Header  |  1991-03-02  |  2KB  |  48 lines

  1. /******** Listing 2 *********************** ARRAY.C ******
  2.  * ARRAY.C : Implementation of dynamic array in C
  3.  * See Listing 1 for copyright terms.      
  4.  ********************************************************/
  5. #include "array.h"
  6. #include <stdio.h>
  7.  
  8. /* an error handler which can only be seen within this file: */
  9. static void error(char * msg) {
  10.   fprintf(stderr, "dynamic_array error: %s\n", msg);
  11.   exit(1);
  12. }
  13.  
  14. /* Call to initialize a dynamic array on the stack: */
  15. void create_array(dynamic_array* da, size_t sz) {
  16.   /* initialize the elements of the structure: */
  17.   da->size = sz;
  18.   /* calloc creates sz items of size int and 
  19.      initializes each to 0 */
  20.   da->vec = calloc(sz, sizeof(int));
  21.   if(da->vec == NULL) error("out of memory in create_array");
  22. }
  23.  
  24. /* Special function to call when creating a dynamic array on the heap: */
  25. dynamic_array* make_heap_array(size_t sz) {
  26.   /* first, create memory to hold the structure: */
  27.   dynamic_array* da = malloc(sizeof(dynamic_array));
  28.   if(da == NULL) error("out of memory in make_heap_array");
  29.   /* then make and initialize the array elements themselves: */
  30.   create_array(da, sz);
  31.   return da;
  32. }
  33.  
  34. /* call to clean up a dynamic array on the stack: */
  35. void free_array(dynamic_array* da) {
  36.   free(da->vec); /* free memory held in struct */
  37. }
  38.  
  39. /* Special function to call when releasing a dynamic array from the heap: */
  40. void release_heap_array(dynamic_array* da) {
  41.   free_array(da);
  42.   free(da); /* free memory used for struct */
  43. }
  44.  
  45. int* value(dynamic_array* da, int index) {
  46.   if(index < 0 || index >= da->size) error("index out of range");
  47.   return &(da->vec[index]);
  48. }