Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!uflorida!haven!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: dynamic arrays (was: Re: lint on V.3) Message-ID: <19409@mimsy.UUCP> Date: 5 Sep 89 13:00:49 GMT References: <1394@redsox.bsw.com> <14064@bloom-beacon.MIT.EDU> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 62 In article <14064@bloom-beacon.MIT.EDU> scs@hstbme.mit.edu (Steve Summit) writes: >(It's beyond me, though, why a production compiler would be using >arrays for symbol tables in the first place, rather than trees or >hash tables.) PCC does better: it uses arrays that are organised into trees and hash tables. :-) There are (sometimes) good reasons. But anyway: > #define NELEM 100 > char *array[NELEM]; becomes > int nalloc = 0; > char **array = NULL; /* simulates char *array[nalloc] */ ... > if(nents >= nalloc) { > nalloc += 10; /* note 1 */ > array = (char **)realloc((char *)array, /* note 2 */ > nalloc * sizeof(char *)); There is (at least) one case in which this will cause subtle breakage. >The nice thing is that no actual references to the array need to >be changed, because the reference array[i] acts the same [4] >whether array is a char *[] or a char **. [and I have to include footnote 4 here] >4. The statement that "the reference array[i] acts the same > whether array is a char *[] or a char **" should NOT be > construed as meaning that pointers are the same as arrays. > They are not, and the compiler will generate different code > for array[i] depending on how array is declared; but the > effect from the user's (author's of the code) point of view is > the same. There is at least one time that the dynamic allocation will cause code to break. Consider this, for instance: int tab[TSIZE]; ... int *p = &tab[k]; ... insert_into_tab(); ... ... use *p ... insert_into_tab() { if (ntab > TSIZE) error("table full"); tab[TSIZE++] = next(); } Now, when we change `tab[SIZE]' as recommended, all of a sudden the use of `*p' becomes incorrect. This is not a particularly unusual situation (and indeed, PCC is full of such references, which is why I never made its tables dynamic myself). This problem can be fixed, but it does take more work. -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163) Domain: chris@mimsy.umd.edu Path: uunet!mimsy!chris