First Year Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Structures and unions

C structures model real-world records with multiple fields; unions let different fields share the same memory for efficient storage.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Engineers often need to group different kinds of data that describe one real-world entity, such as a student (name, roll number, marks) or a sensor reading (value, unit, timestamp). Structures and unions let you model such records cleanly in C and control memory layout. Unions help when only one of several fields is needed at a time, saving memory (useful in embedded systems, protocols, and device drivers).

Key ideas

  • Syntax definition: struct Tag { member_declarations… };
  • A member is a named field declared inside a structure.
  • An instance (or object) of a structure is a variable of that structure type.
  • Access:
    • Use the dot operator . to access a member from a structure variable: s.age.
    • Use the arrow operator -> to access a member through a pointer to a structure: ps->age.
  • Arrays, nesting, and pointers:
    • An array of structures is allowed (e.g., struct Student cls[60];).
    • Nested structures: a structure can contain another structure as a member.
    • Self-referential structure: a structure can contain a pointer to the same structure type (used in linked lists).
  • Typedef:
    • typedef creates an alias name for a type: typedef struct Student Student; or typedef struct { … } Student;. Common pattern: typedef struct Student { /* members */ } Student; then use Student s;.
  • Size, alignment, and padding:
    • sizeof(struct_type) gives the total size in bytes, which is implementation-defined but is at least the sum of member sizes, possibly plus padding.
    • Members are laid out in declaration order. Compilers may insert padding bytes between members to satisfy each member’s alignment requirement.
    • Reordering members can change total size due to padding (important in memory-constrained systems and I/O formats).
  • Assignment and comparison:
    • Whole-structure assignment is allowed: s2 = s1; copies the entire object (including any padding).
    • Direct comparison with == or != is not allowed for structures. Compare members individually.
  • Passing to functions:
    • Structures can be passed by value (copied) or by pointer (address passed). Use const pointer parameters if you will not modify the structure inside the function.
  • Initialization:
    • Initialize with braces in declaration order: struct P p = {10, 20};.
    • Named (designated) initializers like { .y = 20, .x = 10 } are supported in standard C (C99 and later); check your compiler options.
  • Bit-fields:
    • A bit-field is a member of type int, signed int, unsigned int, or _Bool with a specified bit width (other types may be implementation-defined): unsigned int flag:1;.
    • Bit-fields pack multiple small integer members into the same storage unit to save space. Exact layout and alignment of bit-fields are implementation-defined.
    • You can read and write bit-fields like normal integers, but you cannot take their address with &.
  • Unions:
    • A union is a user-defined type where all members share the same memory location. At any moment, only one member is valid to read (the one most recently written).
    • The size of a union is at least the size of its largest member, rounded up for alignment.
    • Typical usage is a tagged union: pair a union with an enum or tag field to record which member is active.
  • Diagram to draw (for exams): memory layout and padding
    • Draw a rectangle representing the structure’s total size in bytes, divided into 1-byte boxes.
    • Label each contiguous block with the member name and its size (e.g., name[20], age(4), pad(…)).
    • Indicate alignment (e.g., int aligned to 4 bytes). Show where padding bytes appear.
  • Safety and portability notes:
    • Do not read a different union member than the one last written; doing so is not portable.
    • Do not assume structure sizes or padding across compilers or platforms; use sizeof and explicit serialization when needed.
    • When interfacing with files or networks, define exact formats and handle endianness explicitly.

Formulas

`struct Tag { type1 member1; type2 member2; /* … */ };`
  • Structure variable declaration: struct Tag var;
  • Combined typedef and definition: typedef struct { type1 m1; type2 m2; } Alias;
  • Member access: var.member (dot), ptr->member (arrow)
  • Array of structures: struct Tag arr[N];
  • Nested structure: struct Outer { struct Inner in; };
  • Self-referential structure: struct Node { int data; struct Node *next; };
  • Initialization: struct P p = {10, 20}; struct P q = { .y = 20, .x = 10 }; // C99 designated initializers
  • Bit-fields: struct Flags { unsigned int a:1; unsigned int b:2; };
  • Union definition and use: union U { int i; float f; char c; }; union U u; u.i = 10; // Only u.i is valid to read now
  • Tagged union pattern: enum Tag { IS_INT, IS_FLOAT }; struct Value { enum Tag tag; union { int i; float f; } data; };
  • sizeof and offsetof: size_t s = sizeof(struct Tag); size_t o = offsetof(struct Tag, member); // needs <stddef.h>

Worked examples

  1. Program: Array of structures, function with pointer parameter, and topper Complete C program that reads student records, computes each student’s average, prints them, and finds the topper and class average.
#include <stdio.h>

#define SUBJECTS 3

struct Student {
    char name[20];
    int roll;
    int marks[SUBJECTS];
    float avg;
};

void compute_avg(struct Student *s) {
    int sum = 0;
    for (int i = 0; i < SUBJECTS; i++) sum += s->marks[i];
    s->avg = (float)sum / SUBJECTS; // uses -> operator on pointer to struct
}

int main(void) {
    int n;
    if (scanf("%d", &n) != 1 || n <= 0 || n > 100) return 0;
    struct Student cls[100];

    for (int i = 0; i < n; i++) {
        // Input: name (no spaces), roll, then 3 marks
        if (scanf("%19s %d %d %d %d",
                  cls[i].name, &cls[i].roll,
                  &cls[i].marks[0], &cls[i].marks[1], &cls[i].marks[2]) != 5) return 0;
        compute_avg(&cls[i]);
    }

    // Print each student's average
    for (int i = 0; i < n; i++) {
        printf("%s (Roll %d): Avg = %.2f\n", cls[i].name, cls[i].roll, cls[i].avg);
    }

    // Find topper and class average
    int topper = 0;
    int total_marks = 0;
    for (int i = 0; i < n; i++) {
        if (cls[i].avg > cls[topper].avg) topper = i;
        total_marks += cls[i].marks[0] + cls[i].marks[1] + cls[i].marks[2];
    }
    float class_avg = (float)total_marks / (n * SUBJECTS);

    printf("Topper: %s (Roll %d) with Avg = %.2f\n",
           cls[topper].name, cls[topper].roll, cls[topper].avg);
    printf("Class average = %.2f\n", class_avg);

    return 0;
}

Sample input:

3
Amit 101 78 82 69
Beena 102 91 88 95
Charan 103 60 73 68

Exact output:

Amit (Roll 101): Avg = 76.33
Beena (Roll 102): Avg = 91.33
Charan (Roll 103): Avg = 67.00
Topper: Beena (Roll 102) with Avg = 91.33
Class average = 78.22
  1. Program: Tagged union to store either int or float Complete C program that uses a tagged union to store a value that is either an int or a float, based on user choice.
#include <stdio.h>

enum Tag { IS_INT = 1, IS_FLOAT = 2 };

union Number {
    int i;
    float f;
};

struct Value {
    enum Tag tag;
    union Number data;
};

int main(void) {
    struct Value v;
    int choice;
    if (scanf("%d", &choice) != 1) return 0;
    if (choice == 1) {
        v.tag = IS_INT;
        if (scanf("%d", &v.data.i) != 1) return 0;
    } else if (choice == 2) {
        v.tag = IS_FLOAT;
        if (scanf("%f", &v.data.f) != 1) return 0;
    } else {
        return 0;
    }

    if (v.tag == IS_INT) {
        printf("You entered int: %d\n", v.data.i);
    } else {
        printf("You entered float: %.2f\n", v.data.f);
    }

    return 0;
}

Sample input:

2 3.5

Exact output:

You entered float: 3.50
  1. Program: Bit-fields for simple permissions Complete C program that defines a structure with bit-fields for read, write, and execute permissions, and prints them.
#include <stdio.h>

struct Perm {
    unsigned int read:1;
    unsigned int write:1;
    unsigned int exec:1;
    unsigned int reserved:5; // reserved bits (packing/layout are implementation-defined)
};

int main(void) {
    struct Perm p = {0, 0, 0, 0};
    int r, w, x;
    if (scanf("%d %d %d", &r, &w, &x) != 3) return 0;
    p.read = (r != 0);
    p.write = (w != 0);
    p.exec = (x != 0);

    printf("Permissions: R=%u W=%u X=%u\n", (unsigned)p.read, (unsigned)p.write, (unsigned)p.exec);
    return 0;
}

Sample input:

1 0 1

Exact output:

Permissions: R=1 W=0 X=1

Common mistakes

  • Forgetting & in scanf for numeric members (e.g., scanf("%d", &s.roll);). Array names like s.name already decay to a pointer, so scanf("%s", s.name); is correct (no &).
  • Reading strings with spaces using %s. %s stops at whitespace. Use fgets for names with spaces, and trim newline.
  • Assuming a structure’s sizeof or member offsets are the same on all systems. They depend on compiler and target platform alignment rules. Do not use memcmp to compare two structures for equality; padding bytes can differ even when all members are equal.
  • Accessing a union member different from the one last written. This is not portable and can produce unexpected results.
  • Using bit-fields for hardware or network protocols without checking compiler packing rules. Bit-field layout and endianness are implementation-defined.
  • Passing large structures by value unnecessarily. This copies the entire structure. Prefer passing a pointer when you do not need a copy (and mark it const if you will not modify it).
  • Forgetting to initialize all structure members, leading to indeterminate values. Initialize explicitly or zero-initialize with {0} when suitable.
  • Reordering structure members without checking how it affects padding and alignment, which can silently increase memory usage.

For your exam

  • Short notes: differences between structure and union; padding and alignment; tagged unions; arrays of structures; nested and self-referential structures; structure assignment and parameter passing.
  • Programs: array of structures (e.g., students/employees/products) with functions operating on them; union with a menu selection; bit-fields for flags.
  • Diagrams: draw memory layout of a given structure and show padding between members; show how a union overlays members.
  • Concept checks: what sizeof returns; why == does not work for structures; how -> differs from .; when to use typedef.
  • What a full-marks answer includes:
    • Exact definitions in clear terms, with bold key words and correct syntax snippets.
    • For diagrams: a labeled byte-wise layout showing member sizes and padding positions, with a note on alignment assumptions (e.g., int aligned to 4 bytes on the assumed platform).
    • For programs: complete, compilable C code, correct input handling, and exact output. Use functions to show parameter passing (by value vs pointer) and the -> operator.
    • For union answers: clearly state that only the last-written member may be safely read, and explain the tagged union pattern.
    • For bit-fields: state that width, packing, and order are implementation-defined, and note that addresses of bit-fields cannot be taken.

Quick check

  1. Define a union and explain when it should be used instead of a structure.
  2. How do you access a member price from (a) a structure variable item and (b) a pointer pitem to that structure?
  3. Why can’t two structures be compared with == in C? How should you compare them instead?

Answers: 1) A union groups several members that share the same memory; use it when only one of the members is needed at a time to save memory (e.g., a value that can be int or float). 2) Use item.price and pitem->price. 3) The language does not define == for structures; compare each member individually (write a function to return equal only if all corresponding members match).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?