These are the notes for C episode 12. So far every array held one kind of thing. A student, though, has a name, a roll number and marks: three different types. Here you store a class the obvious way (parallel arrays), watch it mix up students, and invent structures to fix it. You will learn struct, the dot operator, initialisers, typedef, copying a whole struct with =, what you can't do with structs (==, assigning a string), arrays of structs, passing a struct to a function by address, and the arrow operator ->. Every example below was compiled with gcc -O2 -Wno-unused-result main.c -o main -lm (gcc 13, the same command as the SyntaxPilot compiler) and run as shown.
The problem: the class teacher's register
For each student the register has three facts:
| Fact | Example | C type |
|---|---|---|
| Name | Riya | char name[20] (text) |
| Roll number | 12 | int (whole number) |
| Marks | 72 | float (decimal) |
With what we know, a class becomes three parallel arrays: separate arrays where position i in each one belongs to student i. The teacher wants the topper first, so we swap the marks:
#include <stdio.h>
int main() {
char names[3][20] = {"Riya", "Aman", "Kabir"};
int rolls[3] = {12, 7, 21};
float marks[3] = {72, 95, 64};
// put the topper first: swap only the marks
float t = marks[0]; marks[0] = marks[1]; marks[1] = t;
for (int i = 0; i < 3; i++)
printf("%-6s roll %2d: %.0f\n", names[i], rolls[i], marks[i]);
return 0;
}
Output:
Riya roll 12: 95
Aman roll 7: 72
Kabir roll 21: 64
Riya now has Aman's 95. The marks moved, the names and rolls didn't. (%-6s prints the name left-aligned in 6 characters, %2d the roll in 2: just to line things up.)
Why it broke
- One student is spread across three arrays.
- C has no idea those three positions belong together.
- Move one, forget another, and the data is mixed up. With an address and a phone number it would be five arrays to keep in step.
Idea: one box per student, with all three facts inside. Move the box, and everything moves together.
struct: one box for different types
Real-life example: a school ID card.
| At school | In C |
|---|---|
| A blank ID-card design: Name ___ Roll ___ Marks ___ | struct Student { ... };: a new type, a design |
| Riya's filled-in card | struct Student s;: a variable of that type |
| Reading the Roll line of the card | s.roll: the dot picks a member |
A structure (struct) groups variables of different types under one name. The variables inside are its members (or fields). Defining a struct creates a new type; it doesn't create any variable yet.
#include <stdio.h>
struct Student {
char name[20];
int roll;
float marks;
};
int main() {
struct Student s;
s.roll = 12;
s.marks = 91.5;
printf("Roll %d got %.1f\n", s.roll, s.marks);
printf("sizeof = %zu bytes\n", sizeof(s));
return 0;
}
Output:
Roll 12 got 91.5
sizeof = 28 bytes
28 bytes = 20 (name) + 4 (roll) + 4 (marks): one whole student in one place.
Don't forget the semicolon
A struct definition is a statement and ends with };. Without the ;:
main.c:9:1: error: expected ';', identifier or '(' before 'int'
9 | int main() {
| ^~~
The error points at the line after the struct, because that's where gcc notices.
Padding (bonus)
The compiler may add unused padding bytes between members so that each one starts at an address the CPU likes (an int at a multiple of 4). So a struct's size can be bigger than the sum of its members, and member order matters:
#include <stdio.h>
struct A { char c; int n; char d; };
struct B { int n; char c; char d; };
int main() { printf("%zu %zu\n", sizeof(struct A), sizeof(struct B)); return 0; }
Output: 12 8. Always use sizeof, never add the sizes yourself.
Initialising a struct
Give the values in curly braces, in the same order as the members:
struct Student a = {"Riya", 12, 72};
Members you leave out become 0. You can also name them (designated initialisers): struct Student a = {.roll = 12, .name = "Riya"};.
typedef: a short name
Writing struct Student every time is long. Just writing Student:
main.c:10:5: error: unknown type name 'Student'; use 'struct' keyword to refer to the type
10 | Student s;
| ^~~~~~~
| struct
In C the type's full name is struct Student.
Real-life example: a nickname. Rajendra Kumar Sharma is "Raju" to everyone: same person, shorter name. typedef gives a type a nickname:
typedef struct {
char name[20];
int roll;
float marks;
} Student;
Now Student s; works. (typedef works for any type, e.g. typedef unsigned long ulong;.)
Copying a whole struct: the swap that works
One = copies every member of a struct, including the char array inside:
#include <stdio.h>
typedef struct {
char name[20];
int roll;
float marks;
} Student;
int main() {
Student a = {"Riya", 12, 72};
Student b = {"Aman", 7, 95};
Student t = a; a = b; b = t; // swap whole students
printf("%s roll %d: %.0f\n", a.name, a.roll, a.marks);
printf("%s roll %d: %.0f\n", b.name, b.roll, b.marks);
return 0;
}
Output:
Aman roll 7: 95
Riya roll 12: 72
Names, rolls and marks moved together: the parallel-array bug is gone.
What you can't do with a struct
Compare two structs with ==
Student a = {"Riya", 12, 72};
Student b = a;
if (a == b) printf("Same student\n");
main.c:12:11: error: invalid operands to binary == (have 'Student' and 'Student')
C can't compare whole structs. Compare the members that matter: if (a.roll == b.roll).
Assign a string to a char-array member
Student s;
s.name = "Riya";
main.c:12:12: error: assignment to expression with array type
You can't assign to an array (episode 9), and name is a char array. Copy the text in with strcpy from <string.h>:
#include <stdio.h>
#include <string.h>
typedef struct {
char name[20];
int roll;
float marks;
} Student;
int main() {
Student s;
strcpy(s.name, "Riya");
s.roll = 12;
printf("%s %d\n", s.name, s.roll);
return 0;
}
Output: Riya 12.
An array of students
Not three arrays: one array where every slot is a whole student.
| Expression | Means |
|---|---|
cls |
the whole class (array of 3 Students) |
cls[1] |
the whole card of student 1 |
cls[1].marks |
one field of that card |
Square brackets pick the student, the dot picks the field.
#include <stdio.h>
typedef struct {
char name[20];
int roll;
float marks;
} Student;
int main() {
Student cls[3] = {{"Riya", 12, 72}, {"Aman", 7, 95}, {"Kabir", 21, 64}};
int top = 0;
for (int i = 1; i < 3; i++)
if (cls[i].marks > cls[top].marks) top = i;
printf("Topper: %s, roll %d, %.0f marks\n", cls[top].name, cls[top].roll, cls[top].marks);
return 0;
}
Output:
Topper: Aman, roll 7, 95 marks
Pointers to structs and the arrow ->
Structs are passed to functions by value, like everything else in C: the function gets a photocopy.
void add_grace(Student s) {
s.marks = s.marks + 5;
}
...
Student s = {"Kabir", 21, 64};
add_grace(s);
printf("%s: %.0f\n", s.name, s.marks);
Output: Kabir: 64. The grace marks went to the copy (episode 7's problem). Fix from episode 10: pass the address.
#include <stdio.h>
typedef struct {
char name[20];
int roll;
float marks;
} Student;
void add_grace(Student *p) {
(*p).marks = (*p).marks + 5;
}
int main() {
Student s = {"Kabir", 21, 64};
add_grace(&s);
printf("%s: %.0f\n", s.name, s.marks);
return 0;
}
Output: Kabir: 69.
The brackets in (*p).marks are required: . binds tighter than *, so *p.marks would mean *(p.marks). Because this is so common, C has a shortcut, the arrow operator:
p->marksmeans exactly(*p).marks
void add_grace(Student *p) {
p->marks = p->marks + 5;
}
Same output, Kabir: 69. Use . on a struct, -> on a pointer to a struct. Mix them up and gcc suggests the fix:
main.c:10:6: error: 'p' is a pointer; did you mean to use '->'?
10 | p.marks = p.marks + 5;
| ^
| ->
Passing a pointer is also faster for big structs: the function copies 8 bytes (an address) instead of the whole struct.
Structs inside structs
A member can itself be a struct. A date of birth has a day, a month and a year, so make a Date struct and put one inside Student:
#include <stdio.h>
typedef struct {
int day, month, year;
} Date;
typedef struct {
char name[20];
int roll;
Date dob;
} Student;
int main() {
Student s = {"Riya", 12, {14, 11, 2008}};
printf("%s, roll %d, born %02d/%02d/%d\n", s.name, s.roll, s.dob.day, s.dob.month, s.dob.year);
s.dob.year = 2009;
printf("Corrected year: %d\n", s.dob.year);
return 0;
}
Output:
Riya, roll 12, born 14/11/2008
Corrected year: 2009
Chain the dots: s.dob.year is "the year of the date of birth of s". The inner initialiser gets its own braces. (%02d prints at least 2 digits, padding with a 0.) This is called a nested struct.
Common mistakes (and the real gcc messages)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
struct Student { ... } with no ; |
error: expected ';', identifier or '(' before 'int' |
A struct definition ends with ; |
struct Student { ... }; |
Student s; without typedef |
error: unknown type name 'Student'; use 'struct' keyword to refer to the type |
The full name is struct Student |
struct Student s; or typedef |
if (a == b) on structs |
error: invalid operands to binary == (have 'Student' and 'Student') |
C can't compare whole structs | Compare members: a.roll == b.roll |
s.name = "Riya"; |
error: assignment to expression with array type |
name is a char array |
strcpy(s.name, "Riya"); |
p.marks when p is a pointer |
error: 'p' is a pointer; did you mean to use '->'? |
. needs a struct, not an address |
p->marks |
| Passing a struct by value to change it | No error, change is lost | The function got a copy | Pass &s, take Student * |
| Swapping only one parallel array | No error, mixed-up data | The arrays aren't linked | Use an array of structs |
Mini project: class topper and average
The teacher types in four students (name, roll, marks); print the topper and the class average.
#include <stdio.h>
typedef struct {
char name[20];
int roll;
float marks;
} Student;
int main() {
Student cls[4];
float sum = 0;
int top = 0;
for (int i = 0; i < 4; i++) {
scanf("%19s %d %f", cls[i].name, &cls[i].roll, &cls[i].marks);
sum = sum + cls[i].marks;
if (cls[i].marks > cls[top].marks) top = i;
}
printf("Topper: %s (roll %d)\n", cls[top].name, cls[top].roll);
printf("Average: %.2f\n", sum / 4);
return 0;
}
Input:
Riya 12 72
Aman 7 95
Kabir 21 64
Meera 3 88
Output:
Topper: Aman (roll 7)
Average: 79.75
%19sreads at most 19 letters, so the name (plus its'\0') always fits in 20 bytes.cls[i].nameneeds no&: it's achararray, already an address.rollandmarksneed&.
Practice
- Make a
Bookstruct with a title, an author and a price. - Read 5 books and print the cheapest.
- Write
void discount(Book *b, float pct)using->. - Sort 3 students by marks, highest first, swapping whole structs.
Solutions
All four in one program (verified):
#include <stdio.h>
typedef struct {
char title[40];
char author[30];
float price;
} Book;
typedef struct {
char name[20];
int roll;
float marks;
} Student;
void discount(Book *b, float pct) {
b->price = b->price - b->price * pct / 100;
}
int main() {
Book shelf[5];
for (int i = 0; i < 5; i++)
scanf("%39s %29s %f", shelf[i].title, shelf[i].author, &shelf[i].price);
int cheap = 0;
for (int i = 1; i < 5; i++)
if (shelf[i].price < shelf[cheap].price) cheap = i;
printf("Cheapest: %s by %s, Rs %.2f\n", shelf[cheap].title, shelf[cheap].author, shelf[cheap].price);
discount(&shelf[cheap], 10);
printf("After 10%% off: Rs %.2f\n", shelf[cheap].price);
Student s[3] = {{"Riya", 12, 72}, {"Aman", 7, 95}, {"Kabir", 21, 64}};
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2 - i; j++)
if (s[j].marks < s[j + 1].marks) {
Student t = s[j]; s[j] = s[j + 1]; s[j + 1] = t;
}
for (int i = 0; i < 3; i++) printf("%s %.0f\n", s[i].name, s[i].marks);
return 0;
}
Input:
Godaan Premchand 180
Gitanjali Tagore 150
Malgudi Narayan 220
Wings Kalam 199
Ikigai Garcia 350
Output:
Cheapest: Gitanjali by Tagore, Rs 150.00
After 10% off: Rs 135.00
Aman 95
Riya 72
Kabir 64
(%s in scanf stops at a space, so these titles are one word each. Episode 9's fgets handles titles with spaces.)
Quick quiz
What does this print?
typedef struct { int x; } Box;
Box a = {5};
Box b = a;
Box *p = &a;
b.x = 9;
p->x = p->x + 1;
printf("%d %d", a.x, b.x);
- A.
6 9 - B.
10 9 - C.
6 6 - D.
5 9
Answer
A: 6 9. b is a copy of a, so b.x = 9 doesn't touch a. p points at a, so p->x + 1 makes a.x 6. (Verified output: 6 9.)
Interview questions
- What is a structure? How is it different from an array?
- What does
typedefdo? Write atypedef struct. - Can you assign one struct to another with
=? Can you compare them with==? - What is the difference between
.and->? What isp->xequivalent to? - Why must you write
(*p).xwith brackets? - Are structs passed by value or by reference in C? How do you let a function change a struct?
- Why can
sizeof(struct)be larger than the sum of its members' sizes? What is padding? - How do you store a string inside a struct, and how do you set it?
- What are parallel arrays and why are they error-prone?
- Can a struct contain another struct? Can it contain a pointer to its own type?
Glossary
| Term | Meaning | Example |
|---|---|---|
| Parallel arrays | Separate arrays where index i in each belongs to the same item |
names[i], rolls[i], marks[i] |
Structure (struct) |
A user-defined type that groups members of different types | struct Student { ... }; |
| Member (field) | One variable inside a struct | roll in Student |
Dot operator . |
Picks a member of a struct variable | s.marks |
| Initialiser | Values in { } that fill a struct when it's created |
{"Riya", 12, 72} |
| Designated initialiser | An initialiser that names the members | {.roll = 12} |
typedef |
Gives a type a new (usually shorter) name | typedef struct { ... } Student; |
| Struct assignment | a = b; copies every member |
swapping two students |
strcpy |
Copies a string into a char array (<string.h>) |
strcpy(s.name, "Riya") |
| Array of structs | An array where each element is a whole struct | Student cls[3]; |
| Pointer to struct | A pointer holding a struct's address | Student *p = &s; |
Arrow operator -> |
Member access through a pointer; p->x is (*p).x |
p->marks |
| Padding | Unused bytes the compiler adds between members for alignment | struct A is 12, not 6 |
| Nested struct | A struct used as a member of another struct | p.dob.year |
Summary
- Parallel arrays fall out of step; a struct keeps different types together in one box.
- Define it with
struct Name { members };(don't forget the;), use members with.. typedefgives the type a short name:Student s;.a = bcopies a whole struct;==doesn't work, compare members instead.- Strings in a struct:
strcpy, not=. - An array of structs holds a whole class:
cls[i].marks. - Pass
&sto let a function change a struct; through a pointer, usep->member(=(*p).member).
Next episode: Unions and enums: one box that holds one thing at a time, and names instead of magic numbers.