home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #27 / NN_1992_27.iso / spool / comp / lang / c / 16719 < prev    next >
Encoding:
Text File  |  1992-11-18  |  1.7 KB  |  55 lines

  1. Newsgroups: comp.lang.c
  2. Path: sparky!uunet!comp.vuw.ac.nz!actrix!David.Empson
  3. From: David.Empson@bbs.actrix.gen.nz
  4. Subject: Re: 2-D Arrays, Revisited.
  5. Organization: Actrix Information Exchange
  6. Date: Wed, 18 Nov 1992 12:23:42 GMT
  7. Message-ID: <1992Nov18.122342.17477@actrix.gen.nz>
  8. References: <17489@pitt.UUCP>
  9. Sender: David.Empson@actrix.gen.nz (David Empson)
  10. Lines: 43
  11.  
  12. In article <17489@pitt.UUCP> fahad@cs.pitt.edu (Fahad A Hoymany) writes:
  13. > I am writing a function that should accept a 2-D array (hopefully of any
  14. > size), operate on that array, and returns 'anything' to the caller. Please
  15. > don't suggest I use double pointers because I do not want to restrict the 
  16. > users of my function to use them when they are used to declaring arrays
  17. > as : int a[2][5]. 
  18. > What should the formal parameters line look like?
  19.  
  20. int my_array_function(int a[][5], int nrows) {
  21.     /* ... */
  22. }
  23.  
  24. You can refer to array elements within the function as normal, e.g.
  25. a[i][j] will refer to the ith row and jth column.
  26.  
  27. The function should be called with the name of a compatible array.
  28.  
  29.  
  30. In C, only the leftmost dimension can be left unspecified.  All other
  31. dimensions must be fixed.  If you want a 2-D array that varies in both
  32. dimensions, you will have to do something rather more ugly, e.g.:
  33.  
  34. int another_array_function(int a[], int nrows, int ncols) {
  35.     /* To refer to element a[i][j], use: */
  36.     temp = a[i * ncols + j];
  37. }
  38.  
  39. and to call this function, given an array b[10][2], you would use:
  40.  
  41.     temp = another_array_function(b[0], 10, 2);
  42.  
  43. or
  44.  
  45.     temp = another_array_function(&b[0][0], 10, 2);
  46.  
  47.  
  48. Hope this helps.
  49. -- 
  50. David Empson
  51.  
  52. Internet: David.Empson@bbs.actrix.gen.nz    EMPSON_D@kosmos.wcc.govt.nz
  53. Snail mail: P.O. Box 27-103, Wellington, New Zealand
  54.