In the below two lines,
char a[5]={1,2,3,4,5};
char *ptr=(char *)(&a+1);
printf(\"%d\",*(ptr-1));
This prints 5 on screen.Whereas when use
Arrays aren't pointers! Read section 6 of the comp.lang.c FAQ for more information.
Let's look at your second case first, since it's the more "normal" and idiomatic looking. Line by line:
a
containing 5 char
elements.a
) decays into a pointer to its first element in this context. You add 1
to that and assign the result to ptr
. ptr
points to the 2
. No cast is necessary, though you have one.1
from ptr
and then dereference and print - hence you get the 1
.Now, let's address the first case, again line by line:
a
containing 5 char
elements.a
, yielding a char (*)[5]
type pointer. You then add 1
to this pointer - because of pointer arithmetic this new pointer pasts to the byte just after 5
in memory. Then you typecast (required, this time) and assign this value to ptr
.1
from ptr
and then dreference and print. ptr
is a char *
, so this subtraction simply moves the pointer back by one from "one past the end of a
" to point to the last element of a
. Hence you get the 5
.Finally, the reason char *ptr=&a+1;
gives a warning is because C requires conversions between pointer types to have an explicit cast. As mentioned above, &a
is of type char (*)[5]
, not char *
, so to assign that value to a char *
variable, you'll need the explicit cast.