home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #16 / NN_1992_16.iso / spool / comp / lang / c / 11812 < prev    next >
Encoding:
Text File  |  1992-07-31  |  1.6 KB  |  53 lines

  1. Xref: sparky comp.lang.c:11812 comp.lang.pascal:4644
  2. Newsgroups: comp.lang.c,comp.lang.pascal
  3. Path: sparky!uunet!usc!sdd.hp.com!cs.utexas.edu!hermes.chpc.utexas.edu!news.utdallas.edu!veerasam
  4. From: veerasam@utdallas.edu (Jeyakesavan Veerasamy)
  5. Subject: Flexible array indexing in C (like Pascal)
  6. Message-ID: <1992Jul31.140623.9280@utdallas.edu>
  7. Sender: usenet@utdallas.edu
  8. Nntp-Posting-Host: csclass.utdallas.edu
  9. Organization: Univ. of Texas at Dallas
  10. Date: Fri, 31 Jul 1992 14:06:23 GMT
  11. Lines: 40
  12.  
  13.  
  14. When translating Pascal programs to C, this tip may be helpful.
  15.  
  16. Flexible array indexing of pascal really gave lot of problems for me.
  17. (It is common to see negative array indices in scientific pascal programs).
  18. Following macro allocates the equavalent array in C.
  19.  
  20. It basically allocates the memory, returns the pointer
  21. after adjusting it for index range.
  22.  
  23.  
  24. /* Allocates array for which index value low to hi will be legal,
  25.    Only requirement is, low < hi */
  26.  
  27. #define allocate(type,low,hi) \
  28.     ((type *) malloc ( (hi-low+1) * sizeof(type) ) - low)
  29.  
  30.  
  31. /* Example usage */
  32. main()    
  33. {
  34.     char *a;
  35.     int *b;
  36.  
  37.     a = allocate( char, -200, -100 );
  38.     b = allocate( int, 'a', 'z' );
  39.     
  40.     a[-200] = 'A';
  41.     b['a'] = 2;
  42.     b['z'] = 1;
  43. }
  44.  
  45. With regards,
  46. Jey.
  47.  
  48.  ----------------------------------------------------------------------
  49. |  Mail: Jeyakesavan Veerasamy       M.S. Computer Science             |
  50. |        2400 Waterview Pkwy #811    The University of Texas at Dallas |
  51. |        Richardson TX 75080-2263    Email: veerasam@utdallas.edu      |
  52.  ----------------------------------------------------------------------
  53.