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;}
See also  10 Best Apps to Help You Read More Books in Less Time
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist