Is &a[NTHINGS] legal

Brian R. Bainter brb at akgua.ATT.COM
Fri May 6 01:46:56 AEST 1988


>From article <12074 at tut.cis.ohio-state.edu>, by lvc at tut.cis.ohio-state.edu (Lawrence V. Cipriani):
> Is it legal to apply the & (address of) operator to an array
> element that is non-existent?  Given:
> 
> 	sometype a[NTHINGS], *p;
> 
> Should:
> 
> 	for (p = a; p < &a[NTHINGS]; p++)	/* 1 */
> 		...
> be written as:
> 
> 	for (p = a; p <= &a[NTHINGS-1]; p++)	/* 2 */
> 		...
> 
> I like 1 better than 2 since there are fewer characters to
> type and I find it quicker and easier to comprehend.  The
> dpANS says & only applies to objects that are not bit fields
> or have the register qualifier.  In this example, one could
> argue that a[NTHINGS] doesn't even exist so that & should be
> invalid on it.  Will 1 be guaranteed to work in ANSI-C?

I see no problem with the first examle. Taking into consideration
that a is an address and NTHINGS is an offset to that address,
there should be no problem whatsoever with this construct. If C
was a more crude language which made limit checks on arrays, there
might be a problem in doing something like this. C however does not
make any limit checks for arrays. Arrays are nothing more than an
address and an offset. The exception is when you are defining the
array. At this point the compiler needs to know the limit of the
array so that memory may be allocated.

If you have a question with something like this, it may be most
worthwhile to write a test program and try the construct or algorithm
out. In most cases you can't hurt anything, and you may learn
exactly what is going on with the code. Using a source debugger
such as sdb or even printf statements may help.

          Brian R. Bainter



More information about the Comp.lang.c mailing list