prev up next   top/contents search

comp.lang.c FAQ list · Question 6.17

Q: Here's a neat trick: if I write

	int realarray[10];
	int *array = &realarray[-1];
I can treat array as if it were a 1-based array.

A: Although this technique is attractive (and was used in old editions of the book Numerical Recipes in C), it is not strictly conforming to the C Standard. Pointer arithmetic is defined only as long as the pointer points within the same allocated block of memory, or to the imaginary ``terminating'' element one past it; otherwise, the behavior is undefined, even if the pointer is not dereferenced. The code above computes a pointer to memory before the beginning of realarray and could fail if, while subtracting the offset, an illegal address were generated (perhaps because the address tried to ``wrap around'' past the beginning of some memory segment).

Additional links: “Yes, Virginia”

References: K&R2 Sec. 5.3 p. 100, Sec. 5.4 pp. 102-3, Sec. A7.7 pp. 205-6
ISO Sec. 6.3.6
Rationale Sec.

prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North