Originally Posted by
manasij7479
The idea as it seems to me is to find out the distance (in bytes(?)) between two addresses.
Straight subtraction will give you the distance in units, by type:
Code:
int n[2];
printf("%p - %p = %d bytes\n", &n[1], &n[0], (&n[1] - &n[0]) * sizeof(n[0]));
Now try w/ a cast: ((void*)&n[1] - (void*)&n[0]).
Why would the `difference` between different types of pointers have different types ?
I guess for convenience. That way, p++ will always take you to, eg, the next int in an array, and not just the second byte of the current one.
The next paragraph talks about a macro called offsetof for finding the offset of structure members. What is the difference between using it and simply ( *object - *member ) ?
That's backwards (it's member - struct), but you are right, that is the same thing. However, note that you cannot subtract a struct address from a member address without casting, because they are different types. So offsetof() is a little tidier:
Code:
#include <stddef.h>
struct x {
int a;
int b;
};
struct x eg;
printf("using difference: %d bytes\n", (void*)&(eg.b) - (void*)&eg);
printf("using offsetof: %d bytes\n", offsetof(struct x, b));