Determine the size of following structure

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Lil heaven
    New Member
    • Nov 2020
    • 1

    Determine the size of following structure

    Code:
    Struct student
    { int rno ;
       char name[20] ;
       int n1, n2, total ;
    }
    Last edited by Banfa; Nov 18 '20, 08:19 PM. Reason: Added code tags
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    That rather depends on the platform and the packing rules in play which can be changed on some compilers.

    Have you tried using the sizeof operator, it would give you an answer although it will be platform specific.

    Comment

    • dev7060
      Recognized Expert Contributor
      • Mar 2017
      • 656

      #3
      Determine the size of following structure
      Total size = Size of the data members + Padding size

      About padding:
      Padding is implementation-defined. Added between the members and/or at the end to arrange memory and avoid alignment issues. Why padding? Because the processor can read one word at a time (word size = 4 bytes in 32-bit system and 8 in 64-bit system).
      Code:
      #include <stdio.h>
      
      struct student {
        int rno;
        char name[20];
        int n1, n2, total;
      } obj;
      int main() {
        printf("Padding = %d", sizeof(obj)-(4 * sizeof(int) + 20 * sizeof(char)));
        return 0;
      }
      O/P: Padding = 0

      Everything is aligned (multiples of 4).

      Changing to introduce padding:
      Code:
      #include <stdio.h>
      
      struct student {
        int rno;
        char name[19];
        int n1, n2, total;
      } obj;
      int main() {
        printf("Padding = %d\n", sizeof(obj)-(4 * sizeof(int) + 19 * sizeof(char)));
        printf("%u\n", &obj.rno);
        printf("%u\n", &obj.name);
        printf("%u\n", &obj.n1);
        printf("%u\n", &obj.n2);
        printf("%u\n", &obj.total);
        return 0;
      }
      O/P:
      Padding = 1
      3281444928
      3281444932
      3281444952
      3281444956
      3281444960

      The padding of 1 empty byte is added before n1. The order of the data members could change the padding and hence the structure size.

      Comment

      Working...