Pages

Thursday, October 6, 2011

Why size(Structure) differ from sum of actual sizes of individual members

Same Data Members : Different Sizes

struct  MyStructA {
   char a;
   char b;
   int  c;
};

struct MyStructB {
   char a;
   int c;
   char b;
};

int main(void) {
        int sizeA = sizeof(struct MyStructA);
        int sizeB = sizeof(struct MyStructB);

        printf("A = %d\n", sizeA);//->8
        printf("B = %d\n", sizeB);//->12 in arch x86, DevCPP Compiler
        getch();
        return 0;
}
(via : forum)


(from Wiki)

struct student{
  char grade; /* char is 1 byte long */
  int age; /* int is 4 bytes long */
};
 
printf("%zu", sizeof (struct student));
The reason for this is that most compilers, by default, align complex data-structures to a word alignment boundary. In addition, the individual members are also aligned to their respective alignment boundaries. By this logic, the structure student gets aligned on a word boundary and the variable age within the structure is aligned with the next word address. This is accomplished by way of the compiler inserting "padding" space between two members or to the end of the structure to satisfy alignment requirements. This padding is inserted to align age with a word boundary. (Most processors can fetch an aligned word faster than they can fetch a word value that straddles multiple words in memory, and some don't support the operation at all[3]).

This also has roots into the bus size, (which is word size), making the size of structure integral multiple of bus size helps processor fetching the data faster.
How ?? : > i  l update as soon as i get crude answer.

No comments:

Post a Comment