Find size of a struct without using sizeof operator

How will you find the size of a structure in C/C++ language without using sizeof operator.

(Note: sum of sizes of all fields of a structure may not be equal to the exact memory allocated to the structure. See, Method-1 in solution).


Solution:

Method-1: (Erroneous)

You may be tempted to calculate the size of all the fields of structure, then compute the sum of all these sizes and get the result. For example:

        struct Student{
            int rollno;
            char name[25];
            float avgMarks;
        }obj;

You can say that

        size_of_obj = sizeof(int) + 25*sizeof(char) + sizeof(float);

There are 2 problems in this:

We are using sizeof operator to calculate the sizeof fields.. :)

There may be padding along the fields of a structure. This padding is an extra memory which will not be used to store anything, but to optimize the read/write of individual fields of a structure variable. (If a field is stored in two words of memory then it will take 2 reads, but if we leave the space in between so that the field is stored in just one word, the read & write operation will take only one cycle, read more about it here...).

Method-2: (Right method)


Right method is to allocate an array of structure and compare the memory addresses of consecutive elements of an Array:

        struct Student arr[2];
        size_of_struct = (char*)&arr[1] - (char*)&arr[0];

Note that if we don't convert the address to char* then the answer will always be 1 (because it will talk about the memory block & not memory location).

Tags:

CPP C Language

0 Comments

Leave a comment