structures in c programming size of structure
the size of a structure is expected is the total of all data members in the structure.
but in reality the sizeof the structure will show additional bytes.
In C, structures can sometimes occupy more memory than the sum of their individual members due to a concept called padding. This is done to ensure proper alignment of data members in memory for efficient access by the CPU.
Reasons for padding:
Alignment requirements:
Most CPUs prefer to access data that is aligned to specific memory addresses. For example, a 4-byte integer might be required to start at an address that is a multiple of 4.
Performance optimization:
Accessing unaligned data can cause performance penalties, as the CPU might need to perform multiple memory accesses to retrieve the data.
#include <stdio.h>struct myStruct { char c; // 1 byte int i; // 4 bytes};int main() { printf("Size of char: %zu\n", sizeof(char)); printf("Size of int: %zu\n", sizeof(int)); printf("Size of myStruct: %zu\n", sizeof(struct myStruct)); return 0;}
Output
Size of char: 1Size of int: 4Size of myStruct: 8
- The
char
member occupies 1 byte. - The
int
member occupies 4 bytes. - However, the total size of the structure is 8 bytes, not 5 bytes as you might expect. This is because the compiler adds 3 bytes of padding after the
char
member to ensure that theint
member is aligned to a 4-byte boundary.
Comments
Post a Comment