- char *a;
-
char b[10]={"12345789"};
-
a=b;
Can any one tell what actually a[-1] would refer to.
What is the use of it /its common usage.
Your example is will yield either an intermittent bug or a segment fault; but there is a similar construction that does work. The following code excerpt comes from "The Standard C Library" by P.J. Plauger, copyright 1992.
- #include <limits.h>
-
#if EOF != -1 || UCHAR_MAX != 255
-
#error WRONG TOLOWER TABLE
-
#endif
-
static const short tolow_tab[257] = {EOF,
-
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00 - 0x07 */
-
...
-
0x40, 'a', 'b', 'c', 'd', 'e', 'f', 'g', /* 0x40 - 0x47 */
-
...
-
};
-
const short *_Tolower = &tolow_tab[1];
-
-
#define tolower(c) _Tolower[(int)(c)]
-
-
int (tolower)(int c) {
-
return (_Tolower[c]);
-
}
The difference between this example and yours is that the pointer is set to the address of the second element of the array. Thus there is something at offset -1 from the pointer.
For an array variable A with n elements, the index absolutely must not be outside the range from zero to n. Note that you can refer to the address of A[n], but you can't actually try to access that element. The compiler knows if you break these rules.
For a pointer variable, you can use pointer arithmetic to access locations on either side of the location pointed to. Pointer arithmetic can be indicated either by a literal arithmetic expression or through array index format. The compiler doesn't know if your pointer arithmetic expression is meaningful.
Cheers,
donbock