home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!world!dirsolns
- From: dirsolns@world.std.com (Bernard Farrell)
- Subject: Re: Arrays with variable dimensions?
- Message-ID: <C02pwu.93C@world.std.com>
- Organization: Directed Solutions Group
- X-Newsreader: Tin 1.1 PL3
- References: <1992Dec26.220736.22177@news.ysu.edu>
- Date: Wed, 30 Dec 1992 13:10:05 GMT
- Lines: 57
-
- ah017@yfn.ysu.edu (John B. Lee) writes:
- : Is it possible to create an array that would change size according
- : to user input?
- :
- : John Lee
- : usr7245a@cbos.uc.edu
- : ah017@yfn.ysu.edu
- : --
-
- You can do this using the following kind of approach:
-
- #define ARRAY_INCR (20)
-
- float fl_arr[] = NULL; /* This is actually a float * -- no space */
- int fl_max = 0; /* Max. num of values allowed in array. */
- int fl_ind = 0; /* Next slot to use in array. */
- float new_val; /* Holds next inserted element */
- ....
- /* Get the next element and insert it into the 'array' */
- new_val = function_to_get_float_value();
-
- if (fl_ind >= fl_max)
- {
- /* Time to increase the array size */
- fl_arr = (float *) realloc(fl_arr,
- sizeof(fl_arr[0])*(fl_max+ARRAY_INCR) );
- if (NULL == fl_arr)
- {
- /* Out of memory -- we're in trouble */
- print_horrible_error_and_exit();
- }
-
- /* Increment the maximum indicator */
- fl_max += ARRAY_INCR;
-
- } /* If we're out of room in array */
-
- /* Now insert the new value */
- fl_arr[fl_ind++] = new_val;
-
- --------------------------------------
-
- This allows the array to increase in size as required. The
- alternative is to do a malloc(), instead of using realloc(),
- based on a value given at run-time. Note that the above
- code works only when realloc() works as malloc() when the
- first parameter is NULL -- some implementations of realloc()
- do not have this behavior.
-
- Hope this helps.
-
-
- --
- |----------------------------------------------------------|
- | Bernard Farrell | Directed Solutions Group |
- |----------------------------------------------------------|
- | dirsolns@world.std.com | (617) 429-2306 |
-