Jan 142013

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).


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;

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).

  2 Responses to “Find size of a struct without using sizeof operator”

Comments (2)
  1. hi this is Gloria Cartwright,
    thank you for giving example of size of operator for last one week i am looking for this information
    I am a professional blogger, present started writing artilces on job description template

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>