here is code which returns size of struct without using sizeof keyword
#include <iostream>
using namespace std;
struct point{
int x;
int y;
};
struct point pt={0,0};
int main(){
point *ppt=&pt;
unsigned char *p1,*p2;
p1=(unsigned char *)ppt;
p2=(unsigned char *)++ppt;
printf("%d",p2-p1);
return 0;
}
it returns 8 as i understand because sizeof char is 1 byte and this struct contains integer types first it convers it to char using char pointers and returns sizeof char? or?i dont understand exactly how it works
thanks
The cast here happens after the ++
It works because ++ on a pointer increases the pointer the number of bytes equal to the size of the type pointed to. Then you cast to char, because minus divides the difference in pointers by the size of the type (so divide by 1 because it’s now char*).
One caveat if you plan to use this — sizeof is definitely done at compile time where this code may or may not be recognized by the optimizer as being a constant expression.
Also, as pointed out by the commenter and other question, it won’t match sizeof if the type needs alignment (some systems require that types start on memory boundaries divisible by 2, 4, etc).
Finally, (from the comments), once the pointer has been incremented, it is invalid and cannot be used (even for subtracting, comparison — i.e. even in ways that don’t dereference it)
From the C Rationale Document: http://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf