home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #16 / NN_1992_16.iso / spool / comp / lang / c / 11714 < prev    next >
Encoding:
Internet Message Format  |  1992-07-29  |  1.5 KB

  1. Path: sparky!uunet!darwin.sura.net!mips!think.com!barmar
  2. From: barmar@think.com (Barry Margolin)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Pointers outside of array boundary
  5. Date: 29 Jul 1992 18:23:36 GMT
  6. Organization: Thinking Machines Corporation, Cambridge MA, USA
  7. Lines: 22
  8. Message-ID: <156nn8INNe8f@early-bird.think.com>
  9. References: <1992Jul28.180945.22332@hubcap.clemson.edu> <mjd.712419017@hal> <1992Jul29.151518.19815@hubcap.clemson.edu>
  10. NNTP-Posting-Host: telecaster.think.com
  11.  
  12. In article <1992Jul29.151518.19815@hubcap.clemson.edu> mjs@hubcap.clemson.edu (M. J. Saltzman) writes:
  13. >In this case, wasting the 0th element of an array
  14. >seems like a relatively small price to pay, if that's the only way 
  15. >to write 1-based code.
  16.  
  17. But it's not.  You can also use a macro, e.g.
  18.  
  19. #define AREF(array,index) (array)[(index)-1]
  20.  
  21. While this looks like it will require an extra subtraction for every array
  22. access, if the array you're indexing is automatic or global (as opposed to
  23. dynamically allocated by malloc()) then a decent compiler should be able to
  24. optimize it away, by precomputing the constant address array-1 (yes, this
  25. is precisely the address that the original poster was trying to compute in
  26. his C code -- the difference here is that the compiler is doing it, and it
  27. knows whether it's valid for the target architecture, while the application
  28. programmer can stick to writing portable code).
  29. -- 
  30. Barry Margolin
  31. System Manager, Thinking Machines Corp.
  32.  
  33. barmar@think.com          {uunet,harvard}!think!barmar
  34.