Skip to content

Module 7 · Structures, Unions, Enums and typedef — topic 1 of 4

Structures

A struct groups related values of different types — a student's roll number, name and marks — into one object. Learn declaration, initialisation, member access with . and ->, arrays of structs, nesting and padding.

Beginner 18 min read·Lesson 27 of 37 in C Programming

Learning objectives

  • Define structures and create, initialise and copy struct variables
  • Access members with . and through pointers with ->
  • Use arrays of structs and pass structs to functions efficiently

Definition

A structure is a user-defined type consisting of a sequence of named members, possibly of different types, laid out in memory in declaration order (with possible padding between members).

Introduction

A student record has a roll number (int), a name (string) and a CGPA (double). Keeping them in three separate arrays works until you sort one and forget the others. A structure keeps the fields of one record together as a single value.

Structures are C's main tool for modelling real-world entities, and they are the building block of every data structure: a linked-list node is a struct containing data and a pointer to the next node.

Why it matters

Every management-system project — library, bank, hospital, inventory — is built on arrays of structs. You'll use them in most of this course's projects.

Understanding . versus ->, struct copying and padding comes up constantly in C interviews.

Detailed explanation

Define a type with struct Student { int roll; char name[30]; double cgpa; };. The type name is struct Student. Declare variables as struct Student s;.

Initialise with braces in member order, or with designated initialisers: struct Student s = {.roll = 7, .name = "Asha", .cgpa = 8.9};. Unmentioned members become zero.

Access members with the dot operator: s.cgpa. Through a pointer use the arrow: p->cgpa, which means (*p).cgpa.

Unlike arrays, structs can be assigned and passed or returned by value: t = s; copies every member, including embedded arrays. For large structs, pass a pointer (const struct Student *) to avoid copying.

Structs cannot be compared with ==; compare member by member.

The compiler may insert padding so each member is suitably aligned. sizeof(struct) can therefore be larger than the sum of its members. Ordering members from largest to smallest usually reduces padding.

Syntax

C
struct Point {
double x;
double y;
};
struct Point p = {1.5, 2.0};
struct Point q = {.y = 4.0}; /* x is 0 */
p.x = 3.0;
struct Point *ptr = &p;
ptr->y = 9.0; /* same as (*ptr).y */
  • A struct definition ends with a semicolon after the closing brace.
  • Use -> when you have a pointer, . when you have the struct itself.
  • Strings inside structs are char arrays; copy into them with snprintf or strcpy.

Code examples

Defining and using a struct

C
#include <stdio.h>
struct Student {
int roll;
char name[30];
double cgpa;
};
int main(void) {
struct Student s = {101, "Asha Rao", 8.92};
printf("%d %s %.2f\n", s.roll, s.name, s.cgpa);
s.cgpa = 9.10;
struct Student copy = s; /* member-wise copy */
copy.roll = 102;
printf("%d %.2f | %d %.2f\n", s.roll, s.cgpa, copy.roll, copy.cgpa);
return 0;
}
Output
101 Asha Rao 8.92
101 9.10 | 102 9.10

Pointers and the arrow operator

C
#include <stdio.h>
struct Account {
int number;
double balance;
};
void deposit(struct Account *a, double amount) {
a->balance += amount;
}
int main(void) {
struct Account acc = {5001, 1500.0};
deposit(&acc, 250.5);
printf("Account %d: %.2f\n", acc.number, acc.balance);
return 0;
}
Output
Account 5001: 1750.50

More examples

Array of structs, nesting and sorting

C
#include <stdio.h>
#include <stdlib.h>
struct Date { int day, month, year; };
struct Employee {
char name[20];
double salary;
struct Date joined; /* nested struct */
};
int by_salary_desc(const void *a, const void *b) {
const struct Employee *x = a, *y = b;
return (y->salary > x->salary) - (y->salary < x->salary);
}
int main(void) {
struct Employee team[] = {
{"Ravi", 52000, {12, 6, 2021}},
{"Meera", 68000, {3, 1, 2019}},
{"Imran", 61000, {25, 9, 2022}},
};
int n = sizeof team / sizeof team[0];
qsort(team, n, sizeof team[0], by_salary_desc);
double total = 0;
for (int i = 0; i < n; i++) {
const struct Employee *e = &team[i];
printf("%-6s %8.0f joined %02d/%02d/%d\n", e->name, e->salary, e->joined.day, e->joined.month, e->joined.year);
total += e->salary;
}
printf("average salary %.2f\n", total / n);
return 0;
}
Output
Meera     68000  joined 03/01/2019
Imran     61000  joined 25/09/2022
Ravi      52000  joined 12/06/2021
average salary 60333.33

Step-by-step explanation

  • struct Date is nested inside struct Employee, accessed as e->joined.day.
  • The array is initialised with one brace group per employee and an inner group for the date.
  • qsort reorders whole structs; the comparator reads salary through const struct Employee *.
  • const struct Employee *e = &team[i]; avoids copying each struct inside the loop.
  • %02d pads day and month with a leading zero.

Expected output

Running “Array of structs, nesting and sorting” prints exactly:

TextOutput
Meera 68000 joined 03/01/2019
Imran 61000 joined 25/09/2022
Ravi 52000 joined 12/06/2021
average salary 60333.33

Practical applications

  • File formats and network headers are described as C structs.
  • Operating systems describe processes with large structs (Linux's task_struct).
  • Database records in management-system projects are arrays of structs.

Best practices

  • Pass large structs by const pointer, not by value.
  • Use designated initialisers for clarity.
  • Order members from largest to smallest to reduce padding when memory matters.

Common mistakes

Using . on a pointer

Avoid

struct Account *p = &acc;
p.balance = 0;

Prefer

struct Account *p = &acc;
p->balance = 0;

p is a pointer, so its members are reached with -> (or (*p).balance).

Assigning a string to a char array member

Avoid

s.name = "Kiran";

Prefer

snprintf(s.name, sizeof s.name, "%s", "Kiran");

Arrays are not assignable. Copy the characters into the member.

Comparing structs with ==

Avoid

if (a == b) { /* ... */ }

Prefer

if (a.x == b.x && a.y == b.y) { /* ... */ }

C has no struct equality operator; compare the members that matter.

Important notes

  • Anonymous structs and unions inside a struct are standard since C11.
  • A struct may contain a pointer to its own type (struct Node *next;) but not a member of its own type.

Key takeaways

  • A struct groups named members of different types.
  • Use . with a struct and -> with a pointer to a struct.
  • Structs can be copied and returned by value; compare them member by member.

Try it yourself

  1. 1
    Define struct Book { char title[50]; char author[30]; int year; double price; }, read three books and print the most expensive.
  2. 2
    Print sizeof of a struct with members char, int, char and then int, char, char. Explain the difference.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

7 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhich operator accesses a member through a pointer to a struct?
  • BeginnerWhich operation is NOT allowed on two variables of the same struct type?
Practise this topic