Interview Questions

I can treat array as if it were a 1-based array ...

C Interview Questions and Answers


(Continued from previous question...)

I can treat array as if it were a 1-based array ...

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).

(Continued on next question...)

Other Interview Questions