"bluetent" <bl******@gmail.com> wrote:
[ Get a real newsreader, or learn how to use Google properly. I've had
to manually reinstate the context here, because you removed it all. ]
ra********@yahoo.com wrote:
main()
(Implicit int has been removed in C99, btw. Better get used to
explicitly writing int main(void).)
{
static int a[] = {1,2,3};
printf("&a[1]-&a[0]=%u\n",&a[1]-&a[0]);
}
If you compile the above program and run it prints 1.
Why?
When you use "&a[1]-&a[0]", the complier will count how many objects
between a[1] and a[0].
True, but...
If you want to count how many bytes between them, you should use
"(int)&a[1]-(int)&a[0]".
....wrong.
First of all, conversion of pointers to integers is
implementation-defined; the two ints you get are perhaps quite probably
sizeof(int) apart, but this is by no means guaranteed.
Second, an int is not a very good type to use for this, both because it
may not be large enough to hold the result (which would invoke UB), and
because it is signed, possibly resulting in unexpected values in rare
cases. In C99, uintptr_t is the obvious type for this; in C89, I'd use
unsigned long, which is still not ideal, but the best C89 has.
Third, the right solution is to use the properties of char pointers,
i.c., that any pointer can be reliably converted to them because chars
have alignment requirements of 1, and that subtraction of two char
pointers must result in a difference in bytes, again, because
sizeof(char) is 1. So you'd use:
printf("&a[1]-&a[0]=%u\n", (char *)&a[1]-(char *)&a[0]);
Richard