Pointer Arithmetic In C

Like the ++ increment operator, the - subtraction operator with pointers also takes into account the size of the objects being pointed to. Specifically, the result returned is the number of bytes difference in the pointer values divided by the size of the pointed-to object (12, in your example). So the difference is 12 bytes, divided by size 12, or 1.


If you really want to know the difference cast each pointers to a (char*) and then to (int) and then subtract. That should give you the answer.

This code gives you the absolute value:

printf("%d\n", abs((int)((char*)q) - (int)((char*)p)));

Remember to include math.h.

Edit: As pointed out in a comment we don't need a double cast. Casting each pointerpointer to an int and then subtracting gives the same answer as the (unecessary) double casting above.

printf("%d\n", abs((int)(q) - (int)(p)));