Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to count the offset of different data type in struct?

I know that different data type will allign. But I can’t figure out why the size of this structure is 12.

#include <stdio.h>

struct ABC{
    char a; 
    char b; 
    int k;  
    char c; 
};

int main()
{
    struct ABC a;
    printf("%lu\n", sizeof(a)); //12
    return 0;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Ok it works like this

Here are the rules:

chars are aligned to 1 byte

ints are aligned to 4 bytes

The entirety of the struct must be aligned to a multiple of the largest element.

the final struct will be

struct ABC
{
    char a; // Byte 0
    char b; // Byte 1
    char padding0[2]; // to align the int to 4 bytes
    int k;  // Byte 4
    char c; // Byte 5
    char padding1[3]; // align the structure to the multiple of largest element.
    // largest element is int with 4 bytes, the closest multiple is 12, so pad 3 bytes more.
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading