home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!cs.utexas.edu!usc!sol.ctr.columbia.edu!ira.uka.de!Germany.EU.net!nixpbe!news.sni.de!snibln!berta!root
- From: root@berta.bln.sni.de (0000-Admin(0000))
- Subject: Re: Two-dimensional Array
- Message-ID: <kurs0.721385792@berta>
- Sender: news@snibln.sni.de (Network News)
- Organization: Siemens Nixdorf Informationssysteme AG, Berlin, Germany
- References: <1992Nov6.163315.20337@kakwa.ucs.ualberta.ca>
- Date: Tue, 10 Nov 1992 08:56:32 GMT
- Lines: 60
-
- niu@prancer.eche.ualberta.ca (Shaohua Niu) writes:
-
- >I am trying to use dynamic memory allocation for two-dimesional
- >matrices and the code fragment is as follows:
-
- >typedef float **MATRIX;
-
- >MATRIX calloc_matrix(int row, int col)
- >{
- > int i;
- > MATRIX mat;
- > mat = calloc(row, sizeof(float *));
- > if (mat==NULL) exit(1);
- > for (i=0; i<row; i++) {
- > mat[i] = calloc(col, sizeof(MATRIX));
- > if (mat[i]==NULL) exit(1);
- > }
- > return mat;
- >}
-
- >when this is called with row=9 and col=9, the fucntion works for the
- >pointer mat[0] to mat[6], but for mat[7], it exited abnormally to DOS,
- >with an error message saying memory allocation error, and the DOS
-
- If you want to allocate 2-dim Arrays, then all elemnts of the array have to
- been alloacte in subsequent memory locations. A Pointer to the first Elemnt of
- a two dim Array is not equivalent to a pointer to pointer.
-
- i.e.
- double matrice[10][5];
-
- matrice is of datatype double (*)[5]. An all 50 Elemnts of the Array are allocated
- beginning at that location. so better do:
- typedef void *MATRIX;
-
- MATRIX calloc_matrix(int row, int col)
- {
- int i;
- MATRIX mat;
- mat = calloc(row*col, sizeof(float));
- if (mat==NULL) exit(1);
- else
- return mat;
- }
-
- Use of mat:
-
- main()
- {
- float (*mat1)[5]; /* pointer to 1st Element of mat */
- mat1=calloc_matrix(10,5);
-
- mat1[1][3]=1.2;
- mat1[5][4]=1.3;
- :
- :
- }
- Lars Eisenblatt
- usually lars@pfm.rmt.sub.org
-
-