Today, my classmate asked me a pointer subtraction problem, originally did not think carefully, record the relevant experience, thank the classmate
The source code is as follows:
1#include <stdio.h>2 3 intMain ()4 {5 6 inta[]={0,1};7 int*p,*Q;8 9 Tenp=&a[0]; Oneq=&a[1]; A -printf"%x%x\n\n", p,q); - theprintf"%x\n\n", Q-p); - - return 0; -}
The second line of output found to be 1, the classmate said that since an int accounted for 4 bytes, and the pointer output address is also a difference of four bytes, but why the subtraction will output 1?
I don't know, then, to test, to improve the code, to change the int type to char (char to one byte), the output is the same, the difference is 1.
Why is it?
To improve the original code, add an int type M variable, (in fact, it should be obvious that the problem, but not notice, so look down)
The value of the local variable m is viewed at the VS2012 breakpoint, and it is found that:
So, finally found the problem.
The addition and subtraction of pointers is handled in the C language (subject only, others regardless):
Such as:
int *ptr;
Ptr+n;
Then the compiler does the following:
Add the address of the pointer to n sizeof (the type of the pointer), in this case, sizeof (int);
So no matter what type of pointer it is, the result of the addition and subtraction is necessarily a number of integers (of course, if it makes sense, if two pointers are not relevant you are useless);
So, the addition and subtraction of pointers is the calculation of the whole number of sizeof (pointer type) on the basis of the original pointer, so the result must be an int, (of course, within the range of int).
That's what I think. Thanks to the following authors, refer to the link:
Http://blog.chinaunix.net/uid-24784130-id-2578030.html