home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!munnari.oz.au!metro!atom.ansto.gov.au!teslab!andrew
- From: andrew@teslab.lab.oz.au (Andrew Phillips)
- Newsgroups: comp.std.c
- Subject: Re: Allocating memory like an array
- Message-ID: <4492@teslab.lab.oz.au>
- Date: 9 Nov 92 23:26:43 GMT
- References: <1992Nov5.203939.1323@fcom.cc.utah.edu>
- Organization: Technology Services, Chief Secretary's Dept, Sydney
- Lines: 34
-
- This should really be in comp.lang.c, shouldn't it?
-
- tim@osiris.usi.utah.edu (Tim Burns 581-4439) writes:
- : Does anyone out there have a routine which does dynamic memory allocation
- : which forces allocation __exactly__ the same as array allocation? Or,
- : can anyone give me a tip on how I might begin constructing such a utility?
-
- The syntactic equivalence of pointers and arrays is a major problem of C.
-
- /* array of L arrays of M doubles */
- double A[L][M];
-
- gives a continguous block of memory, as does:
-
- /* pointer to array of M doubles */
- double (*A)[M];
-
- /* Allocate L arrays of M doubles */
- A = (double (*)[M])malloc(L * sizeof(*A));
- if (L != 0 && M != 0 && A == (double (*)[M])0) .... //error
-
-
- /* cf. char s[10]; and char *s = malloc(sizeof(*s)); ... */
-
- However, the array of pointers to arrays example you gave (from
- Numeric Recipes in C?) has a lot to commend it. One major advantage
- is if the array is large there may not be enough contiguous memory to
- allocate a two-dimensional array but it may be allocated in smaller
- chunks of one-d arrays.
-
- Of course, if you are calling library routines that require two-d
- arrays there's not much you can do.
- --
- Andrew Phillips (andrew@teslab.lab.oz.au) Phone +61 (Aust) 2 (Sydney) 287 6551
-