home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #26 / NN_1992_26.iso / spool / comp / std / c / 3000 < prev    next >
Encoding:
Internet Message Format  |  1992-11-09  |  1.6 KB

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