home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #27 / NN_1992_27.iso / spool / comp / lang / c / 16855 < prev    next >
Encoding:
Internet Message Format  |  1992-11-19  |  2.0 KB

  1. Path: sparky!uunet!mcsun!uknet!edcastle!festival!ajmy
  2. From: ajmy@festival.ed.ac.uk (A Myles)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: 2-D Arrays Problem Solved
  5. Message-ID: <28439@castle.ed.ac.uk>
  6. Date: 20 Nov 92 09:24:35 GMT
  7. References: <17514@pitt.UUCP>
  8. Sender: nntpusr@castle.ed.ac.uk
  9. Lines: 52
  10.  
  11. Sorry I missed the start of this thread...
  12.  
  13. I had this problem recently, and noticed from scrutiny of the as code
  14. that if you define the array using 2 doses of malloc() (one array
  15. of pointers, say the rows, to arrays of whatever type you want
  16. to store, which will be the columns)
  17.  
  18. (i.e. just like argv)
  19.  
  20. then the function will expand:
  21.  
  22. int    **foo;
  23. /* whole buncha mallocs in here */
  24. foo[bar][qux] = ... etc
  25.  
  26. correctly by evaluating the expression as (precedence rules)
  27.  
  28. (foo[bar])[qux]
  29. ^         ^
  30. base of   element of 1d array
  31. column
  32.  
  33. so you trade-off having the array scattered through memory for not
  34. having to use array[one index * a size + another index] stuff, or defining
  35. all bar one of the array dimensions - not great if you need dynamic
  36. array sizing.
  37. Remember the bounds!!!
  38.  
  39. Unfortunately, when passing such a beastie to a function, I found
  40. I sometimes needed to use ***array as the arg. to allow for the fact that
  41. the original 2-d array was defined as **array, and I wanted to
  42. set up the array in the function so passed &array to it to allow
  43. the base address to be loaded into array for use in the calling
  44. function upon return. (arfle barfle gloop?)
  45.  
  46. this manifests itself as (in fn)
  47.  
  48. /* set base of whole shebang to pointer array */
  49. *_base = (type**)malloc(ONEDIMENSION * sizeof(type*));
  50. /* allocate pointers to data space */
  51. (*_base)[element] = (type*)malloc(NEXTDIMENSION * sizeof(type));
  52. /* fill data */
  53. (*_base)[x][y] = the actual data;
  54.  
  55. it seems to work ok, but i can see it all ending in tears...
  56.  
  57. I haven't actually timed it, but i think the array of array method
  58. may be faster since it is two look-ups rather than a multiply and
  59. look-up for those on micro-coded-i-cant-multiply-integers-in-one-clock
  60. machines, though the allocation will be slower (mallocs)
  61.  
  62. Andy.
  63.