More 2D array woes...
Amateurgrammer
eychaner at suncub.bbso.caltech.edu
Mon Mar 4 16:48:05 AEST 1991
A followup to my followup...
eychaner at suncub.bbso.caltech.edu (Amateurgrammer) writes:
>>eychaner at suncub.bbso.caltech.edu writes:
>>>Here we go again, warm up the flame guns...
>>>
>>>Ok, suppose I have an array like
>>> char strings[NUMBER][SIZE];
>>>How do I add more strings to this array, i.e. make it larger, portably and
>>>easily. I can't realloc it, since it's not a pointer! Argh!
Some poeple have complained that this is in the FAQ; well, I did read the
FAQ beforehand and the solutions it gives either result in a non-contiguous
array or make it VERY DIFFICULT to make the array larger. The following
solution is MUCH better (though a little more opaque) than the ones in the
FAQ, and IMHO should be included there.
>Well, actually, Chris Torek (torek at ee.lbl.gov) pointed out that the "cheap
>and dirty way" (my phrase, not his) of doing this is to declare
>
> char (*dynamic)[N];
> dynamic = (char (*)[N]) malloc (M * N);
>
>where N is the number of items in each row of the array, and M is the
>number of rows. This array can then be accessed by
>
> dynamic [x][y] = SOME_CHAR;
>
>and reallocated by
>
> dynamic = realloc (dynamic, NEWSIZE * N);
>
>so you CAN do it in C. It's just a little tricky. Ok, a LOT tricky.
Also, I would like to point out that to call realloc (to add a new row to
the array) with a function could be (I HOPE I got this right, PLEASE):
void increase_array (char (**array)[N], int *num_of_elements)
{
*array = (char (*)[N]) realloc (*array, ++(*num_of_elements) * N);
}
This is called as:
char (*dynamic)[N];
int num_elem;
increase_array (&dynamic, &num_elem);
If your compiler lets you call realloc() with NULL, set dynamic = NULL and
num_elem to 0 to add the FIRST element.
This is VERY powerful, and is MUCH better than the FAQ answer. It is also
EXACTLY what I wanted. So the FAQ is not the be-all and end-all of C.
Neither is C++ (which some people suggested).
:-)
Glenn Eychaner - Big Bear Solar Observatory - eychaner at suncub.bbso.caltech.edu
"You Have the Right to Remain DEAD."
-The Simpsons
More information about the Comp.lang.c
mailing list