home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #31 / NN_1992_31.iso / spool / comp / lang / c / 18982 < prev    next >
Encoding:
Internet Message Format  |  1992-12-29  |  2.0 KB

  1. Path: sparky!uunet!olivea!spool.mu.edu!sgiblab!news.kpc.com!kpc!hollasch
  2. From: hollasch@kpc.com (Steve Hollasch)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Accessing a dynamical 3-D field
  5. Summary: Multi-dimensional array element access
  6. Message-ID: <1992Dec29.190722.20859@kpc.com>
  7. Date: 29 Dec 92 19:07:22 GMT
  8. References: <1992Dec29.142134.25641@Informatik.TU-Muenchen.DE>
  9. Sender: usenet@kpc.com
  10. Organization: Kubota Pacific Computer, Inc.
  11. Lines: 32
  12.  
  13. backscha@Informatik.TU-Muenchen.DE (Martin Backschat) writes:
  14. | In my program I use 3-D fields of doubles with variable bounds.
  15. | This field is implemented as an array of doubles which is allocated
  16. | dynamically with malloc.
  17. | To access for example the [i][j][k] component in the field f of dimension
  18. | U,V,W I have to write   f[i*V*W + j*W + k].
  19. | Is it somehow possible to declare and allocate a 3-D field u (of doubles) with
  20. | variable bounds, allocated by malloc, in such a way that it can be accessed
  21. | with u[i,j,k] (with type casting)?
  22.  
  23.     Quite possibly, but to what advantage?  When the compiler performs a
  24. mutli-dimensional array access, it does this exact computation to yield the
  25. address of the element in question.  There are _some_ CPU's that have
  26. instructions to handle (non-general) 2D arrays, but I don't think there are
  27. many (if any) CPU's that have a single instruction to do a 3D array access.
  28.  
  29.     So, if you WERE able to typecast this to a multi-dimensional array (I
  30. tried to find a way but gave up), the compiler would still generate this
  31. code.  What I would do is to just write a macro, e.g.:
  32.  
  33.         #define FIELD(array,i,j,k) \
  34.             array [((((i) * V) + (j)) * W) + (k)]
  35.  
  36.     So then you could just do "FIELD(f,i,j,k)" to refer to a given element.
  37. Note the way that I computed the index takes one less multiply than the
  38. formula you listed.
  39.  
  40. ______________________________________________________________________________
  41. Steve Hollasch                                   Kubota Pacific Computer, Inc.
  42. hollasch@kpc.com                                 Santa Clara, California
  43.