简体   繁体   中英

Why char* type casting is important to get sizeof a variable?

If we have,

int p;
int res;
res= (char*)(&p+1)-(char*)(&p)
printf("size of p= %d",res);

So, the size of p will print 4. Which is the correct answer.

But, if I don't use (char*) , for example,

res=(&p+1)-(&p)

I then got res=1 as output. So, why is this (char*) type casting important to get the size of the p variable.

When I print the value of (&p+1) and (&p) , the difference is 4, but when I print the difference it outputs 1.

Arithmetic with pointers always operates in multiples of the size of the element , not bytes. This is because expressions like array[2] act the same as *(array + 2) . If array is of type int * , then both array[2] and *(array + 2) should refer to the same element. If array + 2 pointed two bytes after array , it would point in the middle of the first element. So instead, the compiler does something like *((int *)((char *)array + 2 * sizeof(int))) .

The same thing happens for pointer subtraction, to maintain the basic properties of addition and subtraction. Given int *p = array + 2 , then p points to the third element. Then, if you compute p - array , then logically, it should equal 2 (because if z = x + y , then z - x = y ).

Further, because the C standard requires the size of char to be 1, casting the pointers to char * will give you the difference in bytes (technically, in char s, but the two terms are usually interchangeable).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM