devxlogo

Determine Object Size Without Using the sizeof() Operator

Determine Object Size Without Using the sizeof() Operator

The sizeof() operator gives you the number of bytes required for storing an object. It also operates on a data type or a value.

Another way of determining the size of an object is to use pointer arithmetic, as in the following example:

struct point {    long x, y;};int main(){    struct point pt = {0}, *ppt = &pt;    unsigned char *p1 = NULL, *p2 = NULL;    size_t size = 0;    p1 = (unsigned char*)(ppt);    p2 = (unsigned char*)(++ppt);    size = p2 - p1; // size is now 8 bytes (2 longs)    // same as sizeof(struct point) or sizeof(pt)    return 0;}

devx-admin

Share the Post: