0
0
Cprogramming~30 mins

Structure vs union comparison - Hands-On Comparison

Choose your learning style9 modes available
Structure vs Union Comparison
📖 Scenario: Imagine you are organizing information about a simple electronic device. You want to store either its serial number or its manufacturing date, but not both at the same time to save memory.
🎯 Goal: You will create a struct and a union to hold device information, then compare their sizes to understand how they use memory differently.
📋 What You'll Learn
Create a struct named DeviceStruct with two members: an int serialNumber and a char manufactureDate[10].
Create a union named DeviceUnion with the same two members: an int serialNumber and a char manufactureDate[10].
Declare variables of type DeviceStruct and DeviceUnion.
Print the sizes of DeviceStruct and DeviceUnion using sizeof.
Print the values stored in the union after assigning to each member to observe how data overlaps.
💡 Why This Matters
🌍 Real World
Understanding structs and unions helps when working with hardware devices, network protocols, or file formats where memory usage and data layout matter.
💼 Career
Many programming jobs require knowledge of memory management and data structures, especially in embedded systems, systems programming, and performance-critical applications.
Progress0 / 4 steps
1
Create the struct and union definitions
Write the definitions for a struct named DeviceStruct and a union named DeviceUnion. Both should have an int serialNumber and a char manufactureDate[10].
C
Need a hint?

Use struct and union keywords to define the types with the exact member names and types.

2
Declare variables of the struct and union
Declare a variable named deviceS of type struct DeviceStruct and a variable named deviceU of type union DeviceUnion.
C
Need a hint?

Use the exact variable names deviceS and deviceU with their respective types.

3
Assign values to deviceU members to observe overlap
Assign 12345 to deviceU.serialNumber. Then assign the string "20240601" to deviceU.manufactureDate using strcpy. Include #include <string.h> at the top.
C
Need a hint?

Remember to include #include <string.h> to use strcpy.

4
Print sizes and values to compare struct and union
Inside main, print the sizes of DeviceStruct and DeviceUnion using sizeof. Then print deviceU.serialNumber and deviceU.manufactureDate to see how the union stores data.
C
Need a hint?

The serialNumber value will change after copying the string because the union shares memory.