0
0
Embedded Cprogramming~20 mins

Struct packing and alignment in Embedded C - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Struct Packing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of struct size with default alignment
What is the output of the following C code when printed with sizeof(s)?
Embedded C
#include <stdio.h>
#include <stddef.h>

struct S {
    char c;
    int i;
};

int main() {
    struct S s;
    printf("%zu", sizeof(s));
    return 0;
}
A12
B5
C8
D16
Attempts:
2 left
💡 Hint
Think about how the compiler aligns the int after the char.
Predict Output
intermediate
2:00remaining
Effect of #pragma pack(1) on struct size
What is the output of the following C code when printed with sizeof(s)?
Embedded C
#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;
}
A16
B8
C12
D5
Attempts:
2 left
💡 Hint
Packing removes padding bytes.
🔧 Debug
advanced
2:30remaining
Why does this struct cause unexpected padding?
Consider this struct and its size output. Why does it have unexpected padding bytes?
Embedded C
struct S {
    char c1;
    double d;
    char c2;
};

// sizeof(S) printed is 24 on a 64-bit system.
ABecause double requires 8-byte alignment, padding is added after c1 and c2.
BBecause the struct is packed with #pragma pack(1).
CBecause the compiler ignores alignment rules for double.
DBecause char variables always cause 8 bytes of padding each.
Attempts:
2 left
💡 Hint
Think about alignment requirements of double and where padding is inserted.
📝 Syntax
advanced
1:30remaining
Identify the syntax error in struct packing directive
Which option contains a syntax error in using #pragma pack to pack a struct?
A
#pragma pack(2)
struct S { char c; int i; };
B
#pragma pack 1
struct S { char c; int i; };
C
#pragma pack(1)
struct S { char c; int i; };
#pragma pack()
D
#pragma pack(push, 1)
struct S { char c; int i; };
#pragma pack(pop)
Attempts:
2 left
💡 Hint
Check the syntax of #pragma directives carefully.
🚀 Application
expert
3:00remaining
Calculate struct size with mixed types and packing
Given the struct below with #pragma pack(1), what is the size of struct S?
Embedded C
#pragma pack(1)
struct S {
    char c;
    short s;
    int i;
    char arr[3];
};
#pragma pack()
A10
B12
C11
D14
Attempts:
2 left
💡 Hint
Add sizes of each member without padding due to packing.