sizeof(s)?#include <stdio.h> #include <stddef.h> struct S { char c; int i; }; int main() { struct S s; printf("%zu", sizeof(s)); return 0; }
The struct has a char (1 byte) followed by an int (usually 4 bytes). The compiler adds padding after the char to align the int on a 4-byte boundary. So total size is 8 bytes.
sizeof(s)?#include <stdio.h> #pragma pack(1) struct S { char c; int i; }; #pragma pack() int main() { struct S s; printf("%zu", sizeof(s)); return 0; }
Using #pragma pack(1) tells the compiler to pack the struct without padding. So the size is the sum of the sizes of char (1 byte) and int (4 bytes) = 5 bytes.
struct S {
char c1;
double d;
char c2;
};
// sizeof(S) printed is 24 on a 64-bit system.The double needs to be aligned on an 8-byte boundary. After char c1 (1 byte), 7 bytes of padding are added before double d. After char c2, 7 bytes of padding are added to make the struct size a multiple of 8.
Option B is invalid because #pragma pack requires parentheses around the argument, e.g., #pragma pack(1). Writing #pragma pack 1 is a syntax error.
#pragma pack(1), what is the size of struct S?#pragma pack(1) struct S { char c; short s; int i; char arr[3]; }; #pragma pack()
With #pragma pack(1), no padding is added. Sizes: char (1) + short (2) + int (4) + char[3] (3) = 10 bytes.