Nearby lessons

99 of 124

C - Structure Introduction

A structure groups related variables of different types under one name. Learn why C needs them, how one struct replaces a fistful of parallel arrays, and where they sit alongside arrays and unions.

The Problem Structures Solve

Suppose you must store a student's name, roll number and marks. Without structures you need three separate variables — and three more for the next student:

Example01
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 /* Three loose variables per student */
6 char name1[30] = "Rahul";
7 int roll1 = 101;
8 float marks1 = 85.5f;
9 
10 char name2[30] = "Priya";
11 int roll2 = 102;
12 float marks2 = 91.0f;
13 
14 printf("%s %d %.1f\n", name1, roll1, marks1);
15 printf("%s %d %.1f\n", name2, roll2, marks2);
16 
17 /* Nothing in the language says these belong together */
18 return 0;
19}
Output
Rahul 101 85.5
Priya 102 91.0

Why Parallel Arrays Are Worse

Parallel arrays look tidier and are far more fragile. Three arrays indexed by the same number only stay in step if every single operation touches all three. Sort one and forget the others, and Rahul's roll number is now attached to Priya's marks — with no compiler error and no crash.
Example02
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 char names[3][30] = {"Rahul", "Priya", "Amit"};
6 int rolls[3] = {101, 102, 103};
7 float marks[3] = {85.5f, 91.0f, 78.0f};
8 
9 /* Suppose we swap two students by name only... */
10 char temp[30];
11 for (int i = 0; i < 30; i++) { temp[i] = names[0][i]; }
12 for (int i = 0; i < 30; i++) { names[0][i] = names[1][i]; }
13 for (int i = 0; i < 30; i++) { names[1][i] = temp[i]; }
14 /* ...and forget rolls and marks */
15 
16 for (int i = 0; i < 3; i++)
17 printf("%-8s %d %.1f\n", names[i], rolls[i], marks[i]);
18 
19 printf("\nPriya now has Rahul's roll number. No error was reported.\n");
20 return 0;
21}
Output
Priya    101  85.5
Rahul    102  91.0
Amit     103  78.0

Priya now has Rahul's roll number. No error was reported.

The Structure Solution

In simple words: a structure is a container you design yourself. You tell C "a Student is a name, a roll number and marks", and from then on those three travel together as a single value that can be copied, passed and returned as one thing.
Example03
CCode Cell
1#include <stdio.h>
2 
3struct Student {
4 char name[30];
5 int roll;
6 float marks;
7};
8 
9int main()
10{
11 struct Student s1 = {"Rahul", 101, 85.5f};
12 struct Student s2 = {"Priya", 102, 91.0f};
13 
14 printf("%s %d %.1f\n", s1.name, s1.roll, s1.marks);
15 printf("%s %d %.1f\n", s2.name, s2.roll, s2.marks);
16 
17 /* One assignment moves all three members */
18 struct Student copy = s1;
19 printf("Copy: %s %d %.1f\n", copy.name, copy.roll, copy.marks);
20 return 0;
21}
Output
Rahul 101 85.5
Priya 102 91.0
Copy: Rahul 101 85.5

An Array of Structures Cannot Drift

Swap two records and every member moves together. The bug from the parallel-array example simply cannot happen:

Example04
CCode Cell
1#include <stdio.h>
2 
3struct Student {
4 char name[30];
5 int roll;
6 float marks;
7};
8 
9int main()
10{
11 struct Student list[3] = {
12 {"Rahul", 101, 85.5f},
13 {"Priya", 102, 91.0f},
14 {"Amit", 103, 78.0f}
15 };
16 struct Student temp;
17 int i;
18 
19 temp = list[0]; /* one swap, all members */
20 list[0] = list[1];
21 list[1] = temp;
22 
23 for (i = 0; i < 3; i++)
24 printf("%-8s %d %.1f\n", list[i].name, list[i].roll,
25 list[i].marks);
26 return 0;
27}
Output
Priya    102  91.0
Rahul    101  85.5
Amit     103  78.0

Structure vs Array

They answer different questions. "How many of the same thing?" is an array. "What parts make up one thing?" is a structure:

ArrayStructure
Member typesAll identicalCan differ
AccessBy index: a[2]By name: s.marks
SizeFixed at declarationFixed by the definition
Assignable as a wholeNoYes
Passed to a functionAs a pointer (decays)By value (copied)
ModelsA listA record
Example05
CCode Cell
1#include <stdio.h>
2 
3struct Point { int x, y; };
4 
5int main()
6{
7 int a[3] = {1, 2, 3};
8 int b[3];
9 
10 struct Point p1 = {10, 20};
11 struct Point p2;
12 
13 /* b = a; ERROR: arrays are not assignable */
14 p2 = p1; /* structures are */
15 
16 printf("Array copied by hand : ");
17 for (int i = 0; i < 3; i++) { b[i] = a[i]; printf("%d ", b[i]); }
18 
19 printf("\nStruct copied in one go: (%d, %d)\n", p2.x, p2.y);
20 return 0;
21}
Output
Array copied by hand : 1 2 3
Struct copied in one go: (10, 20)

Real-World Records

Almost anything you would put on a paper form maps onto a structure:

Example06
CCode Cell
1#include <stdio.h>
2 
3struct Date { int day, month, year; };
4struct Book { char title[50]; char author[30]; float price; };
5struct Employee{ int id; char name[30]; float salary; struct Date joined; };
6 
7int main()
8{
9 struct Book b = {"The C Programming Language", "Kernighan", 550.0f};
10 struct Employee e = {7, "Kavya", 62000.0f, {15, 6, 2021}};
11 
12 printf("Book : %s by %s, Rs %.2f\n", b.title, b.author, b.price);
13 printf("Staff: #%d %s, Rs %.2f, joined %d/%d/%d\n",
14 e.id, e.name, e.salary,
15 e.joined.day, e.joined.month, e.joined.year);
16 return 0;
17}
Output
Book : The C Programming Language by Kernighan, Rs 550.00
Staff: #7 Kavya, Rs 62000.00, joined 15/6/2021

Structure vs Union

A structure gives each member its own storage. A union overlays them in the same bytes, so only one is valid at a time:

Example07
CCode Cell
1#include <stdio.h>
2 
3struct SBox { int i; float f; char c; };
4union UBox { int i; float f; char c; };
5 
6int main()
7{
8 struct SBox s;
9 union UBox u;
10 
11 s.i = 10; s.f = 2.5f; s.c = 'A'; /* all three survive */
12 printf("struct: i=%d f=%.1f c=%c\n", s.i, s.f, s.c);
13 
14 u.i = 10;
15 u.f = 2.5f; /* overwrites u.i */
16 printf("union : f=%.1f (i is now meaningless)\n", u.f);
17 
18 printf("sizeof struct = %zu, sizeof union = %zu\n",
19 sizeof(s), sizeof(u));
20 return 0;
21}
Output
struct: i=10 f=2.5 c=A
union : f=2.5 (i is now meaningless)
sizeof struct = 12, sizeof union = 4

What Structures Give You

Beyond tidiness, a structure buys you four concrete abilities C does not otherwise have:

AbilityWithout structuresWith structures
Copy a recordMember by memberb = a;
Pass a recordMany parametersOne parameter
Return a recordImpossible — use pointersreturn s;
Store many recordsParallel arraysOne array of structs
Example08
CCode Cell
1#include <stdio.h>
2 
3struct Point { int x, y; };
4 
5/* A function can take AND return a whole structure */
6struct Point midpoint(struct Point a, struct Point b)
7{
8 struct Point m;
9 m.x = (a.x + b.x) / 2;
10 m.y = (a.y + b.y) / 2;
11 return m;
12}
13 
14int main()
15{
16 struct Point p = {0, 0}, q = {10, 20};
17 struct Point m = midpoint(p, q);
18 
19 printf("Midpoint of (%d,%d) and (%d,%d) is (%d,%d)\n",
20 p.x, p.y, q.x, q.y, m.x, m.y);
21 return 0;
22}
Output
Midpoint of (0,0) and (10,20) is (5,10)

The Vocabulary

Four words appear constantly in structure code. Getting them straight now saves confusion later:

TermMeaningExample
TagThe name of the structure typeStudent in struct Student
MemberOne variable inside itroll, marks
DefinitionThe blueprint — no memory yetstruct Student { ... };
VariableAn actual instance with memorystruct Student s1;
Example09
CCode Cell
1#include <stdio.h>
2 
3/* tag */
4/* v */
5struct Student { /* <- definition: a blueprint, 0 bytes */
6 char name[30]; /* <- member */
7 int roll; /* <- member */
8 float marks; /* <- member */
9};
10 
11int main()
12{
13 struct Student s; /* <- variable: real memory */
14 
15 printf("One Student occupies %zu bytes\n", sizeof(struct Student));
16 printf("Members: name(%zu) roll(%zu) marks(%zu)\n",
17 sizeof(s.name), sizeof(s.roll), sizeof(s.marks));
18 return 0;
19}
Output
One Student occupies 40 bytes
Members: name(30) roll(4) marks(4)

Common Mistakes

  • Forgetting the struct keyword — in C, Student s; alone is an error; use struct Student s; or a typedef.
  • Missing the semicolon after } — a structure definition ends with };.
  • Expecting sizeof to be the sum of the members — padding usually makes it larger.
  • Comparing with == — structures cannot be compared directly; compare member by member.
  • Confusing a definition with a variable — the definition allocates nothing.
  • Reaching for a union to save space — a union only holds one member at a time.
Trainer's Note: the test for whether you want a structure is the word "and". "A student has a name and a roll number and marks" — structure. "I need fifty students" — array. "It is either an int or a float, never both" — union.
📝 Key Takeaways
  • A structure holds several values of different types as one unit.
  • An array holds many values of the SAME type; a structure holds different types.
  • Members are accessed with the dot operator.
  • A structure models a real-world record — a student, a book, a point.
  • Every member gets its own memory, unlike a union.

🧠 Test Your Knowledge

4 Questions
Progress: 0 / 4