0
0
Embedded Cprogramming~30 mins

Struct packing and alignment in Embedded C - Mini Project: Build & Apply

Choose your learning style9 modes available
Struct packing and alignment
📖 Scenario: You are working on a small embedded device that communicates sensor data. To save memory and send data efficiently, you need to understand how struct packing and alignment affect the size of your data structures.
🎯 Goal: You will create a struct representing sensor data, then apply packing to reduce its size, and finally print the size of the struct before and after packing.
📋 What You'll Learn
Create a struct called SensorData with three fields: char id, int value, and char status.
Create a variable called data of type SensorData.
Create a packed version of the struct called PackedSensorData using __attribute__((packed)).
Print the size of SensorData and PackedSensorData using sizeof.
💡 Why This Matters
🌍 Real World
Embedded systems often have limited memory and bandwidth. Understanding struct packing helps save memory and send data efficiently over networks.
💼 Career
Many embedded software jobs require knowledge of memory layout and optimization techniques like struct packing to write efficient low-level code.
Progress0 / 4 steps
1
Create the SensorData struct
Create a struct called SensorData with these exact fields in this order: char id, int value, and char status. Then declare a variable called data of type SensorData.
Embedded C
Need a hint?

Remember to define the struct with the fields in the exact order and then declare a variable of that struct type.

2
Create a packed version of the struct
Create a packed struct called PackedSensorData with the same fields and order as SensorData. Use __attribute__((packed)) after the struct definition. Then declare a variable called packedData of type PackedSensorData.
Embedded C
Need a hint?

Use __attribute__((packed)) right after the closing brace of the struct definition.

3
Calculate sizes of structs
Create two variables: sizeNormal and sizePacked. Assign sizeof(data) to sizeNormal and sizeof(packedData) to sizePacked.
Embedded C
Need a hint?

Use sizeof operator on the variables data and packedData.

4
Print the sizes of both structs
Use printf to print the sizes stored in sizeNormal and sizePacked. Print exactly these two lines:
Size of SensorData: X
Size of PackedSensorData: Y
where X and Y are the values of sizeNormal and sizePacked respectively.
Embedded C
Need a hint?

Use printf with %u to print unsigned integers and include a newline \n.