Unit 2 · Lesson 427 minAcademic review pending

Model one thing with several fields

Group related values with structures, understand shared union storage, and name states with enumerations.

Choose explanation

After this lesson

You should be able to

  • Define, initialize, and use a structure and an array of structures.
  • Explain when union and enum representations are appropriate.
01

A record with one identity

A structure groups fields that belong to one conceptual record, even when their types differ. A Student can contain a roll number, name, and score. The dot operator selects a field from a structure object.

An array of structures represents many records with the same shape. First choose an element by index, then a field: students[i].score. Copying one structure to another copies its fields, including embedded arrays.

Student record
struct Student {
    int rollNumber;
    char name[40];
    double score;
};

struct Student student = {23, "Anu", 87.5};
printf("%s: %.1f\n", student.name, student.score);
02

Shared storage and named states

All union members share the same storage, so only the currently intended member should be read. A union saves space when a value may be one of several representations, but the program must track which representation is active.

An enum gives readable names to integral states. enum Status { PENDING, ACTIVE, DONE }; is clearer than unexplained numbers. An enum improves expression of intent but does not itself validate every possible integer assignment.

Try it yourself

Design a Book structure with an integer id, title up to 59 characters, and price.

Need a hint?

A 59-character string needs a 60-byte char array for the terminator.

Check the worked solution

Use int id, char title[60], and double price.

struct Book {
    int id;
    char title[60];
    double price;
};

Quick check

What is special about storage in a union?

Select an answer to check your thinking.

Why this lesson exists

Syllabus mapping

Structures · Unions · Arrays of structures · Enumeration data types

Maps to course outcomes CO3, CO5.