Path: utzoo!news-server.csri.toronto.edu!cs.utexas.edu!usc!jarthur!nntp-server.caltech.edu!suncub.bbso.caltech.edu!EYCHANER From: eychaner@suncub.bbso.caltech.edu (Amateurgrammer) Newsgroups: comp.lang.c Subject: Re: More 2D array woes... Message-ID: <1991Mar4.064805.22220@nntp-server.caltech.edu> Date: 4 Mar 91 06:48:05 GMT References: <1991Mar3.235114.12154@nntp-server.caltech.edu>,<1002@caslon.cs.arizona.edu>,<1991Mar4.030849.16054@nntp-server.caltech.edu> Sender: news@nntp-server.caltech.edu Reply-To: eychaner@suncub.bbso.caltech.edu Organization: Big Bear Solar Observatory, Caltech Lines: 57 A followup to my followup... eychaner@suncub.bbso.caltech.edu (Amateurgrammer) writes: >>eychaner@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@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@suncub.bbso.caltech.edu "You Have the Right to Remain DEAD." -The Simpsons