home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #31 / NN_1992_31.iso / spool / comp / lang / c / 19019 < prev    next >
Encoding:
Text File  |  1992-12-30  |  2.1 KB  |  69 lines

  1. Newsgroups: comp.lang.c
  2. Path: sparky!uunet!world!dirsolns
  3. From: dirsolns@world.std.com (Bernard Farrell)
  4. Subject: Re: Arrays with variable dimensions?
  5. Message-ID: <C02pwu.93C@world.std.com>
  6. Organization: Directed Solutions Group
  7. X-Newsreader: Tin 1.1 PL3
  8. References: <1992Dec26.220736.22177@news.ysu.edu>
  9. Date: Wed, 30 Dec 1992 13:10:05 GMT
  10. Lines: 57
  11.  
  12. ah017@yfn.ysu.edu (John B. Lee) writes:
  13. : Is it possible to create an array that would change size according
  14. : to user input?
  15. : John Lee
  16. : usr7245a@cbos.uc.edu
  17. : ah017@yfn.ysu.edu
  18. : -- 
  19.  
  20. You can do this using the following kind of approach:
  21.  
  22. #define   ARRAY_INCR    (20)
  23.  
  24. float fl_arr[] = NULL;   /*  This is actually a float * -- no space  */
  25. int   fl_max = 0;        /*  Max. num of values allowed in array.  */
  26. int   fl_ind = 0;        /*  Next slot to use in array.   */
  27. float new_val;           /*  Holds next inserted element  */
  28. ....
  29.   /*  Get the next element and insert it into the 'array'  */
  30.   new_val = function_to_get_float_value();
  31.  
  32.   if (fl_ind >= fl_max)
  33.   {
  34.     /* Time to increase the array size */  
  35.     fl_arr = (float *) realloc(fl_arr,
  36.                    sizeof(fl_arr[0])*(fl_max+ARRAY_INCR) );
  37.     if (NULL == fl_arr)
  38.     {
  39.        /* Out of memory -- we're in trouble  */
  40.        print_horrible_error_and_exit();
  41.     }
  42.  
  43.     /*  Increment the maximum indicator  */
  44.     fl_max += ARRAY_INCR;
  45.  
  46.   }  /*  If we're out of room in array  */
  47.  
  48.   /*  Now insert the new value  */
  49.   fl_arr[fl_ind++] = new_val;
  50.  
  51. --------------------------------------
  52.  
  53. This allows the array to increase in size as required.  The
  54. alternative is to do a malloc(), instead of using realloc(),
  55. based on a value given at run-time.   Note that the above
  56. code works only when realloc() works as malloc() when the
  57. first parameter is NULL -- some implementations of realloc()
  58. do not have this behavior.
  59.  
  60. Hope this helps.
  61.  
  62.  
  63. -- 
  64. |----------------------------------------------------------|
  65. |      Bernard Farrell      |   Directed Solutions Group   |
  66. |----------------------------------------------------------|
  67. |   dirsolns@world.std.com  |       (617) 429-2306         |
  68.