home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #3 / NN_1993_3.iso / spool / comp / lang / c / 20259 < prev    next >
Encoding:
Internet Message Format  |  1993-01-27  |  1.8 KB

  1. Path: sparky!uunet!ferkel.ucsb.edu!taco!gatech!hubcap!ncrcae!ncrhub2!ncrgw2!psinntp!heimdall!thor!scjones
  2. From: scjones@thor.sdrc.com (Larry Jones)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: c and modula2
  5. Message-ID: <567@heimdall.sdrc.com>
  6. Date: 26 Jan 93 16:33:36 GMT
  7. References: <1993Jan25.184916.23553@mcshub.dcss.mcmaster.ca>
  8. Sender: news@heimdall.sdrc.com
  9. Lines: 39
  10.  
  11. In article <1993Jan25.184916.23553@mcshub.dcss.mcmaster.ca>, cs4gp6au@maccs.mcmaster.ca (Lockie      RJ) writes:
  12. > Here's some Modula-2 code:
  13. > TYPE ex = ARRAY[0..10] OF CHAR;
  14. > VAR test : ARRAY[0..10] OF ex;
  15. >     p : POINTER TO ex;
  16. > BEGIN
  17. >   p = ADR(test[0]);
  18. >   INC( p );
  19. >   (* p now points to test[0][1] *)
  20.  
  21. A better translation of this to C than what you gave would be:
  22.  
  23.     typedef char ex[11];    /* [0..10] is 11 elements */
  24.     ex test[11];
  25.     ex *p;
  26.     p = &test[0];   /* or p = test */
  27.     p ++;
  28.     /* p now points to test[1] according to K&R2 pg. 98 */
  29.  
  30. > So, if the above code is correct, the question I have is why does
  31. > incrementing a pointer in C point to the next element in the array?
  32. > while in Modula-2 it doesn't (the pointer needs to be incremented
  33. > by the size of the array element).
  34.  
  35. Because that's the definition of pointer arithmetic in C.  If p points
  36. to an 11 element array and you increment it, doesn't it make sense that
  37. it then points to the next 11 element array?
  38.  
  39. > How does C do that? Is it the compiler?
  40.  
  41. Yes, the compiler does whatever is necessary to meet the definition of
  42. pointer arithmetic.  For an implementation on a traditional linear
  43. address space machine, this corresponds to multiplying the increment
  44. by the size of what the pointer points to and then adding the result
  45. to the address the pointer is currently pointing to.
  46. ----
  47. Larry Jones, SDRC, 2000 Eastman Dr., Milford, OH  45150-2789  513-576-2070
  48. larry.jones@sdrc.com
  49. It's going to be a long year. -- Calvin
  50.