home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!olivea!sgigate!sgiblab!munnari.oz.au!manuel.anu.edu.au!ampl1.anu.edu.au!stg121
- From: stg121@ampl1.anu.edu.au (Stephen Gibson)
- Newsgroups: comp.lang.c
- Subject: Dynamic Allocation of Matrices
- Message-ID: <1jleldINN23f@manuel.anu.edu.au>
- Date: 21 Jan 93 06:08:45 GMT
- References: <1993Jan19.194253.4100@ucc.su.OZ.AU> <1993Jan19.232122.20952@netcom.com> <TMB.93Jan21014916@arolla.idiap.ch>
- Reply-To: stg121@ampl1.anu.edu.au (Stephen Gibson)
- Organization: Australian National University
- Lines: 85
- NNTP-Posting-Host: 150.203.15.16
-
- Dynamic allocation of matrices.
-
- I would like to be able to generate arrays of various sizes and types
- by calling a function such as
-
- memory (array1,array2,array3);
-
- where the prototype could be:
-
- void memory (double **,double **,int **);
-
- From test cases, see below, it appears that only the following works:
-
- array1 = memory ();
-
- What is the difference between
- double **function (void) and void function (double **)
- with respect to double ** ?
-
- Any helpful comments would be appreciated.
-
- Steve.
- -----------------------------------------------------------------------------
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <stddef.h>
-
- 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;
- }
-
- void memory2 (int m, int n, double **array)
- {
- /* case #2 - array passed as a function parameter */
- int i;
- array = (double **) calloc (m,sizeof(double *));
- for (i=0;i<m;i++) array[i] = (double *) calloc (n,sizeof(double));
- }
-
- void main ()
- {
- int i,j,m,n;
- double **a,**b;
-
- printf ("Enter array size m, n -> ");
- scanf ("%d%d",&m,&n);
-
- printf ("Case #1\n");
- a = memory (m,n);
- for (i=0;i<m;i++)
- for (j=0;j<n;j++) a[i][j] = i+j+1;
- for (i=0;i<m;i++) {
- for (j=0;j<n;j++) printf (" %lg",a[i][j]);
- printf ("\n");
- }
-
- printf ("Case #2\n");
- memory2 (m,n,b);
- for (i=0;i<m;i++)
- for (j=0;j<n;j++) b[i][j] = i+j+1;
- for (i=0;i<m;i++) {
- for (j=0;j<n;j++) printf (" %lg",b[i][j]);
- printf ("\n");
- }
- exit (EXIT_SUCCESS);
- }
-
-
- -------- compilation on DEC 5000/125 ---
- cc -o helpme helpme.c
- -------- execution ---------------------
- helpme
- Enter array size m, n -> 2 3
- Case #1
- 1 2 3
- 2 3 4
- Case #2
- Segmentation fault
-