⚡0 XP🔥0

Structures, Unions and Enums

Lesson 11 of 13 ⏱ 5 min read ✎ 2 exercises ❓ 4-question quiz ▶ Runs C

Group related data with struct, use typedef, arrays of structures, nested structs, pointers to structs (->), unions and enums.

Arrays group values of the same type. Real records mix types: a student has a name (string), a roll number (int) and a CGPA (float). A structure (struct) groups such related values into one unit.

Defining and using a structure#

struct Student {        // a new type: "struct Student"
    int roll;           // members (fields)
    char name[30];
    float cgpa;
};

Access members with the dot operator .:

▶ Try it YourselfC
Ctrl + Enter to run
Output
101  Aarav Gupta   8.4
102  Diya Soni     9.1
Size of one Student: 40 bytes
हिंदी में समझें

struct अलग-अलग type के data को एक साथ जोड़ कर एक नया type बनाता है - जैसे एक student का roll (int), नाम (string) और CGPA (float)। Member तक पहुँचने के लिए dot (.) लगाते हैं: s1.name।

Note

The size may be a little more than the sum of the members because the compiler adds padding bytes to keep members aligned in memory for speed.

typedef - a shorter name#

▶ Try it YourselfC
Ctrl + Enter to run
Output
Notebook   x4    180.00
Pen drive  x1    399.00
Bag        x1    850.00
TOTAL          1429.00

That was also an array of structures - the usual way to store a table of records.

Nested structures#

A structure can contain another structure:

▶ Try it YourselfC
Ctrl + Enter to run
Output
Sunita Rao joined on 15/07/2013
Annual salary: 1344000

Pointers to structures and the -> operator#

Passing a big struct by value copies all of it. Passing a pointer is cheaper and lets the function modify the original. With a pointer, use -> instead of .:

▶ Try it YourselfC
Ctrl + Enter to run
Output
After deposit: 7500.00
Insufficient balance
Final balance: 6300.00

Unions#

A union looks like a struct, but all members share the same memory. Only one member holds a meaningful value at a time. Unions save memory in embedded systems and are used to view the same bytes in different ways.

▶ Try it YourselfC
Ctrl + Enter to run
Output
v.i = 65
v.c = Z
sizeof(union) = 4, sizeof(struct) = 12
struct union
Memory each member has its own space all members share one space
Size ≥ sum of members size of the largest member
Use records with many fields one-of-several values, memory saving

Enums - named integer constants#

An enum gives readable names to a set of integer values:

▶ Try it YourselfC
Ctrl + Enter to run
Output
Level value: 2
Fee paid

INTERMEDIATE is 2 because counting continues from BEGINNER = 1. Enums make switch statements and status fields much easier to read than magic numbers.

Summary#

  • struct groups related values of different types; access members with ..
  • typedef gives a type a short name; arrays of structs store tables of records.
  • With a pointer to a struct, use ->; pass pointers to avoid copying and to modify.
  • A union shares one memory area among members; an enum names integer constants.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Topper of the class

Read n students (name and marks) into an array of structures and print the topper: Topper: Kavya (96).

Test input:
4
Rohan 81
Kavya 96
Imran 88
Sneha 74
Expected output:
Topper: Kavya (96)
2

Distance between two points

Using typedef struct { double x, y; } Point; write double distance(Point a, Point b) and print the distance between (1, 2) and (4, 6) as Distance = 5.00.

Expected output:
Distance = 5.00

Quick Quiz

Q1.

How do you access a member through a pointer p to a struct?

Q2.

What is the size of a union?

Q3.

In enum Day {MON, TUE, WED}; what is the value of WED?

Q4.

What does typedef struct { int x, y; } Point; let you write?