home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #3 / NN_1993_3.iso / spool / comp / lang / c / 20007 < prev    next >
Encoding:
Text File  |  1993-01-21  |  2.0 KB  |  56 lines

  1. Newsgroups: comp.lang.c
  2. Path: sparky!uunet!spool.mu.edu!agate!doc.ic.ac.uk!warwick!dcs.warwick.ac.uk!rince
  3. From: rince@dcs.warwick.ac.uk (James Bonfield)
  4. Subject: Re: Dynamic Allocation of Matrices
  5. Message-ID: <1993Jan21.093137.1772@dcs.warwick.ac.uk>
  6. Sender: news@dcs.warwick.ac.uk (Network News)
  7. Nntp-Posting-Host: stone
  8. Organization: Department of Computer Science, Warwick University, England
  9. References: <1993Jan19.194253.4100@ucc.su.OZ.AU> <1993Jan19.232122.20952@netcom.com> <TMB.93Jan21014916@arolla.idiap.ch> <1jleldINN23f@manuel.anu.edu.au>
  10. Date: Thu, 21 Jan 1993 09:31:37 GMT
  11. Lines: 43
  12.  
  13. In <1jleldINN23f@manuel.anu.edu.au> stg121@ampl1.anu.edu.au (Stephen Gibson) writes:
  14.  
  15. > double **memory (int m, int n)
  16. > {
  17. > /* case #1 - array returned from function */
  18. >  int i;
  19. >  double **array;
  20. >  array = (double **) calloc (m,sizeof(double *));
  21. >  for (i=0;i<m;i++) array[i] = (double *) calloc (n,sizeof(double));
  22. >  return array;
  23. > }
  24.  
  25. Of course - this means that if you allocated an array with memory(100,2)
  26. you'll end up consuming a lot more memory than memory(2,100) (due to all the
  27. malloc headers). The FAQ has a better way of managing this sort of thing. It
  28. is possible to use only one malloc (or calloc) if you're really being finicky
  29. about memory usage:
  30.  
  31. double **memory(int m, int n) {
  32.     int i;
  33.     double **array1, **array2;
  34.     array1 = (double **)calloc(m * sizeof(double *) + n * sizeof(double));
  35.     if (array1 == -1)
  36.     return -1;
  37.     else {
  38.     array2 = &array1[m];
  39.     for (i=1; i<m; i++)
  40.         array2[i] = array2[0] + i * n;
  41.     }
  42.     return array2;
  43. }
  44.  
  45. I don't guarantee this to work - it's all untested. But in principle you
  46. should be able to use something like this to allocate one single block of
  47. memory and then use the same memory for all. 
  48.  
  49. Just my half pennies worth...
  50.  
  51.     James
  52. -- 
  53. James Bonfield (jkb@mrc-lmba.cam.ac.uk / rince@dcs.warwick.ac.uk)
  54. Medical Research Council Laboratory of Molecular Biology, Hills Road,
  55. Cambridge, CB2 2QH, England. Tel: 0223 402499   Fax: 0223 412282
  56.