Quiz 2

Structures, Unions, Bit Fields, Typedef

677 words
3 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Structures, Unions, Bit Fields, Typedef ## 🎯 Learning Objectives - Define and use structures to group related data - Differentiate structures from unions - Calculate structure padding and alignment - Use bit fields for packed data * * * ## 1. Structures ### 1.1 Definition and Usage ### 1.2 Typedef ### 1.3 Nested...

Structures, Unions, Bit Fields, Typedef

🎯 Learning Objectives

  • Define and use structures to group related data
  • Differentiate structures from unions
  • Calculate structure padding and alignment
  • Use bit fields for packed data

1. Structures

1.1 Definition and Usage

c
struct Point {
    int x;
    int y;
};
struct Point p1 = {10, 20};         // Initialize
p1.x = 30;                           // Access member
struct Point *pp = &p1;
pp->x = 40;                          // Access via pointer (arrow operator)

1.2 Typedef

c
typedef struct {
    int x;
    int y;
} Point;
Point p1 = {10, 20};  // No need for 'struct' keyword

1.3 Nested Structures

c
typedef struct {
    Point top_left;
    Point bottom_right;
} Rectangle;
Rectangle r = {{0, 0}, {100, 200}};
int area = (r.bottom_right.x - r.top_left.x) *
           (r.bottom_right.y - r.top_left.y);

2. Structure Padding and Alignment

c
struct Example1 {
    char c;      // 1 byte (offset 0)
    int i;       // 4 bytes (offset 4, not 1!)
    short s;     // 2 bytes (offset 8)
};  // Total: 12 bytes (not 7!)
struct Example2 {
    int i;       // 4 bytes (offset 0)
    short s;     // 2 bytes (offset 4)
    char c;      // 1 byte (offset 6)
};  // Total: 8 bytes (packed better!)
Padding rules:
  • Each member is aligned to its size (int → 4-byte boundary)
  • Structure size is aligned to the largest member's size
  • Reorder members to minimize padding

3. Unions

c
typedef union {
    int i;
    float f;
    char c;
} Number;
Number n;
n.i = 42;
printf("%d\n", n.i);   // 42
printf("%f\n", n.f);   // Garbage! (same memory interpreted as float)
n.f = 3.14;
printf("%f\n", n.f);   // 3.14
printf("%d\n", n.i);   // Garbage!
Size of union = size of largest member (4 bytes for Number above).

4. Bit Fields

c
typedef struct {
    unsigned int is_valid : 1;   // 1 bit
    unsigned int type : 3;       // 3 bits (values 0-7)
    unsigned int size : 4;       // 4 bits (values 0-15)
    unsigned int reserved : 24;  // Remaining 24 bits
} Flags;  // Total: 4 bytes (packed)
Flags f = {1, 5, 10};  // valid=1, type=5, size=10

5. 📝 Practice Questions

Q1: Why does sizeof(struct { char a; int b; }) return 8 instead of 5?
Answer: Structure padding: the int b requires 4-byte alignment, so 3 padding bytes are added after char a to align b to offset 4. Total = 1 (a) + 3 (padding) + 4 (b) = 8 bytes. Q2: What is the difference between a structure and a union?
Answer: In a structure, all members occupy separate memory locations (total size = sum of members + padding). In a union, all members share the same memory (total size = largest member). Writing to one union member overwrites all others. Q3: How can you minimize structure padding?
Answer: Order members from largest to smallest (doubles first, then ints, then shorts, then chars). This minimizes gaps because each member can be placed after the previous one without violating alignment constraints. Q4: What is a bit field and when would you use it?
Answer: A bit field allows specifying the exact number of bits for a member. Used for packed data structures (device registers, network headers, file format headers) where every bit matters. Q5: Write a self-referential structure (linked list node).
c
typedef struct Node {
    int data;
    struct Node *next;  // Pointer to same struct type
} Node;

Node *head = NULL;
Node *new_node = malloc(sizeof(Node));
new_node->data = 42;
new_node->next = head;
head = new_node;

6. 🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.