Newsgroups: comp.lang.c Path: utzoo!sq!msb From: msb@sq.sq.com (Mark Brader) Subject: Re: realloc primer Message-ID: <1991Feb12.212340.19850@sq.sq.com> Organization: SoftQuad Inc., Toronto, Canada References: <1991Feb10.004053.27161@athena.mit.edu> Date: Tue, 12 Feb 91 21:23:40 GMT Lines: 64 In an otherwise excellent article, Steve Summit (scs@adam.mit.edu) writes: > The transformation from fixed-size to dynamically-allocated is > simple: just change the array to a pointer, and add another > variable keeping track of how many slots have been allocated. > (... you [may not] even need the extra variable. ...) > > With one exception, no appearances of the global array (which is > now actually a pointer) in the rest of the code have to be > changed, because pointers can be subscripted the same as arrays ... > One thing to beware of when using realloc is that the array can > (and usually will) move around in memory, invalidating any other > pointers to elements within it. (This is the "one exception" I > alluded to above.) There is in fact a second important exception: sizeof. For instance, given "int arr[N];", some people prefer to write if (i < sizeof arr / sizeof arr[0]) arr[i++] = new_item; else error...; rather than if (i < N) arr[i++] = new_item; else error...; because in the second form you have to look back to the declaration to verify that that N means what you think it does. And such expressions may occur in other places, such as loop headers. A still worse case is this one: if (restoring) fread (arr, sizeof arr, 1, fp); ...; if (saving) fwrite (arr, sizeof arr, 1, fp); Here the *file format* was designed for a fixed-size array, and if it is to be replaced by a dynamic one, the format will have to be changed so that a count can be read from the file before the array itself. And while you're fixing *those* problems, you can also correct the fread and fwrite calls, which should probably look more like this: count = fread ((char *) arr, size, 1, fp); if (count < 1) { fprintf (stderr, "%s: error reading %s..."...); exit(1); } (In ANSI C the type "char *" becomes "void *", and the cast can be removed anyway if a prototype is in scope. Whether it is desirable is a matter of style. It's harmless to leave a char * cast in anyway.) -- Mark Brader "It's simply a matter of style, and while there SoftQuad Inc., Toronto are many wrong styles, there really isn't any utzoo!sq!msb, msb@sq.com one right style." -- Ray Butterworth This article is in the public domain.