Saturday, February 2, 2013

implement your own sizeof() operator

#define mysizeof(data) (char *)(&data+1)-(char *)(&data)

When you increment a T*, it moves sizeof(T) bytes. This is because it doesn't make sense to move any other value: if I'm pointing at an int that's 4 bytes in size, for example, what would incrementing less than 4 leave me with? A partial int mixed with some other data: nonsensical.

http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/pointer.html

The formula used is rather simple. Assume that p1 and p2 are both pointers of type T *. Then, the value computed is:
    ( p2 - p1 ) == ( addr( p2 ) - addr( p1 ) ) / sizeof( T )


int c[3]={1,2,3};
cout<<&c+1<<" "<<&c<<endl;
cout<<(char*)(&c+1)-(char*)(&c)<<endl;//print 12  but if change to int* c it prints 4
int * arr[ 12 ] ;
int ** ptr = arr ;
cout<<(char*)(ptr+1)-(char*)ptr<<endl; //print 4

a more naive example:

int days[] = {1,2,3,4,5};
 int *ptr2 = days;
 printf("%u\n", sizeof(days));
 printf("%u\n", sizeof(ptr));

No comments:

Post a Comment