c++ - What is the meaning of "difference of memory address?" -


consider

#include <cstdio>  int main() {     char a[10];     char *begin = &a[0];     char *end = &a[9];     int = end - begin;     printf("%i\n", i);     getchar(); } 

#include <cstdio>  int main() {     int a[10];     int *begin = &a[0];     int *end = &a[9];     int = end - begin;     printf("%i\n", i);     getchar(); } 

#include <cstdio>  int main() {     double a[10];     double *begin = &a[0];     double *end = &a[9];     int = end - begin;     printf("%i\n", i);     getchar(); } 

all above 3 examples print 9

may know, how should interpret meaning of 9. mean?

the compiler automatically calculate pointer arithmetic based on type of pointer, why cant perform operation using void* (no type information) or mixed pointer type (ambiguous type).

in msvc2008 (and in other compiler believe), syntax interpreted calculate amount of element difference between 2 pointer.

int = end - begin; 00411479  mov         eax,dword ptr [end]  0041147c  sub         eax,dword ptr [begin]  0041147f  sar         eax,3  00411482  mov         dword ptr [i],eax  

since subtraction followed right-shifting, result round-down, hence guarantee n element can fit memory space between 2 pointer (and there might unused gap). proven in code below yield result of 9 too.

int main() {     double a[10];     double *begin = &a[0];     char *endc = (char*)&a[9];     endc += 7;     double *end = (double*)endc;     int = end - begin;     printf("%i\n", i);     getchar();      return 0; } 

Comments

Popular posts from this blog

unicode - Are email addresses allowed to contain non-alphanumeric characters? -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

c++ - Convert big endian to little endian when reading from a binary file -