home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!spool.mu.edu!agate!doc.ic.ac.uk!warwick!dcs.warwick.ac.uk!rince
- From: rince@dcs.warwick.ac.uk (James Bonfield)
- Subject: Re: Dynamic Allocation of Matrices
- Message-ID: <1993Jan21.093137.1772@dcs.warwick.ac.uk>
- Sender: news@dcs.warwick.ac.uk (Network News)
- Nntp-Posting-Host: stone
- Organization: Department of Computer Science, Warwick University, England
- References: <1993Jan19.194253.4100@ucc.su.OZ.AU> <1993Jan19.232122.20952@netcom.com> <TMB.93Jan21014916@arolla.idiap.ch> <1jleldINN23f@manuel.anu.edu.au>
- Date: Thu, 21 Jan 1993 09:31:37 GMT
- Lines: 43
-
- In <1jleldINN23f@manuel.anu.edu.au> stg121@ampl1.anu.edu.au (Stephen Gibson) writes:
-
- > double **memory (int m, int n)
- > {
- > /* case #1 - array returned from function */
- > int i;
- > double **array;
- > array = (double **) calloc (m,sizeof(double *));
- > for (i=0;i<m;i++) array[i] = (double *) calloc (n,sizeof(double));
- > return array;
- > }
-
- Of course - this means that if you allocated an array with memory(100,2)
- you'll end up consuming a lot more memory than memory(2,100) (due to all the
- malloc headers). The FAQ has a better way of managing this sort of thing. It
- is possible to use only one malloc (or calloc) if you're really being finicky
- about memory usage:
-
- double **memory(int m, int n) {
- int i;
- double **array1, **array2;
- array1 = (double **)calloc(m * sizeof(double *) + n * sizeof(double));
- if (array1 == -1)
- return -1;
- else {
- array2 = &array1[m];
- for (i=1; i<m; i++)
- array2[i] = array2[0] + i * n;
- }
- return array2;
- }
-
- I don't guarantee this to work - it's all untested. But in principle you
- should be able to use something like this to allocate one single block of
- memory and then use the same memory for all.
-
- Just my half pennies worth...
-
- James
- --
- James Bonfield (jkb@mrc-lmba.cam.ac.uk / rince@dcs.warwick.ac.uk)
- Medical Research Council Laboratory of Molecular Biology, Hills Road,
- Cambridge, CB2 2QH, England. Tel: 0223 402499 Fax: 0223 412282
-