home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #26 / NN_1992_26.iso / spool / comp / lang / c / 16267 < prev    next >
Encoding:
Text File  |  1992-11-10  |  1.8 KB  |  72 lines

  1. Newsgroups: comp.lang.c
  2. Path: sparky!uunet!cs.utexas.edu!usc!sol.ctr.columbia.edu!ira.uka.de!Germany.EU.net!nixpbe!news.sni.de!snibln!berta!root
  3. From: root@berta.bln.sni.de (0000-Admin(0000))
  4. Subject: Re: Two-dimensional Array
  5. Message-ID: <kurs0.721385792@berta>
  6. Sender: news@snibln.sni.de (Network News)
  7. Organization: Siemens Nixdorf Informationssysteme AG, Berlin, Germany
  8. References: <1992Nov6.163315.20337@kakwa.ucs.ualberta.ca>
  9. Date: Tue, 10 Nov 1992 08:56:32 GMT
  10. Lines: 60
  11.  
  12. niu@prancer.eche.ualberta.ca (Shaohua Niu) writes:
  13.  
  14. >I am trying to use dynamic memory allocation for two-dimesional
  15. >matrices and the code fragment is as follows:
  16.  
  17. >typedef float **MATRIX;
  18.  
  19. >MATRIX calloc_matrix(int row, int col)
  20. >{
  21. >  int i;
  22. >  MATRIX mat;
  23. >  mat = calloc(row, sizeof(float *));
  24. >  if (mat==NULL) exit(1);
  25. >  for (i=0; i<row; i++) {
  26. >    mat[i] = calloc(col, sizeof(MATRIX));
  27. >    if (mat[i]==NULL) exit(1);
  28. >  }
  29. >   return mat;
  30. >}
  31.  
  32. >when this is called with row=9 and col=9, the fucntion works for the
  33. >pointer mat[0] to mat[6], but for mat[7], it exited abnormally to DOS,
  34. >with an error message saying memory allocation error, and the DOS
  35.  
  36. If you want to allocate 2-dim Arrays, then all elemnts of the array have to
  37. been alloacte in subsequent memory locations. A Pointer to the first Elemnt of
  38. a two dim Array is not equivalent to a pointer to pointer.
  39.  
  40. i.e.
  41. double matrice[10][5];
  42.  
  43. matrice is of datatype double (*)[5]. An all 50 Elemnts of the Array are allocated
  44. beginning at that location. so better do:
  45. typedef void *MATRIX;
  46.  
  47. MATRIX calloc_matrix(int row, int col)
  48. {
  49.   int i;
  50.   MATRIX mat;
  51.   mat = calloc(row*col, sizeof(float));
  52.   if (mat==NULL) exit(1);
  53.    else
  54.    return mat;
  55. }
  56.  
  57. Use of mat:
  58.  
  59. main()
  60. {
  61.     float        (*mat1)[5]; /* pointer to 1st Element of mat */
  62.    mat1=calloc_matrix(10,5);
  63.  
  64.     mat1[1][3]=1.2;
  65.     mat1[5][4]=1.3;
  66.     :
  67.     :
  68. }
  69. Lars Eisenblatt
  70. usually lars@pfm.rmt.sub.org
  71.  
  72.