Consider
#include <cstdio>
int main() {
char a[10];
char *begin = &a[0];
char *end = &a[9];
int i = end - begin;
printf("%i\n", i);
getchar();
}
#include <cstdio>
int main() {
int a[10];
int *begin = &a[0];
int *end = &a[9];
int i = end - begin;
printf("%i\n", i);
getchar();
}
#include <cstdio>
int main() {
double a[10];
double *begin = &a[0];
double *end = &a[9];
int i = end - begin;
printf("%i\n", i);
getchar();
}
All the above three examples also print 9
May I know, how I should interpret the meaning of 9. What does it mean?
the compiler will automatically calculate pointer arithmetic based on type of pointer, which is why you cant perform operation using
void*(no type information) or mixed pointer type (ambiguous type).In MSVC2008 (and in most other compiler i believe), the syntax is interpreted as calculate the amount of element difference between two pointer.
Since the subtraction is followed by a right-shifting, the result will be round-down, hence guarantee N element can fit into memory space between two pointer (and there might be unused gap). This is proven in code below which yield result of 9 too.