Another silly question

Guy Harris guy at auspex.auspex.com
Fri Apr 28 20:18:27 AEST 1989


 >My CS instructor and I disagree about a certain moot point.  I have a text
 >book which says that
 >
 >	*(a + i)	and	a[i]
 >
 >are equivalent, given an array a, and int index i ... each gives the
 >value stored in a[i].

Your textbook is correct.

 >But he says that
 >
 >	*(a + i)
 >
 >is non-standard and would not expect it do go far on all _real_ C compilers
 >(_real_ meaning those compilers that are somewhat devoted to K & R or ANSI).

Your instructor is incorrect.

 >He expects that many compilers would instead add the value of i to the
 >pointer a, and then reference the item stored there.

Yes, which gives the value stored in a[i].  "The pointer a" is really
"the pointer-valued expression generated by the conversion of the
array-valued expression 'a' into a pointer-valued expression that points
to the first element of the array 'a'"; if you add "i" to that
pointer-valued expression, you get a pointer to the "i"th element of the
array "a".  Dereference that pointer, and you get the "i"th element of
the array "a", or "a[i]".

 >I say that the compiler's smart enough to realize what we're trying
 >to achieve, and won't do something like
 >
 >	* (char *) ( (int) a + i )
 >
 >which he thinks it will probably do on most machines.

You are correct; he is incorrect.  Perhaps he does not understand how
pointer addition works in C?  If you add an integral value N to a pointer,
it doesn't increment the address in that pointer by N storage units
(bytes on byte addressible machine, etc.), it can be thought of as
incrementing the address by N objects of the type to which that pointer
points.  In C, pointers have types, and those types are significant.



More information about the Comp.lang.c mailing list