Making a type of your own
A structure groups related fields of different types under one name, which is the proper fix for the parallel arrays of Unit III.
After this lesson
You should be able to
- Define a structure type and declare variables of it.
- Access and assign members with the dot operator.
- Explain why an array of structures is safer than parallel arrays.
One student, one variable
A student has a roll number, a name, and marks — three different types that belong together. A structure lets you say that once and then treat a student as a single value.
typedef gives the type a short name so you can write Student instead of struct student everywhere. Members are reached with a dot.
#include <string.h>
typedef struct {
int roll;
char name[40];
int marks;
} Student;
Student s;
s.roll = 101;
strcpy(s.name, "Kavya"); /* a string member needs strcpy */
s.marks = 87;
printf("%d %s %d\n", s.roll, s.name, s.marks);An array of structures
Student class[3]; gives three complete students. Now class[1].marks is that student's marks, and the roll number cannot drift away from the marks because they live in the same box.
This is the parallel-array problem solved. Sorting an array of structures moves whole students, so a student's name can never end up beside someone else's score.
Student class[3] = {
{101, "Kavya", 87},
{102, "Ravi", 64},
{103, "Sneha", 91}
};
for (int i = 0; i < 3; i++)
printf("%-8s %3d\n", class[i].name, class[i].marks);Structures can contain structures
A member may itself be a structure. A Date inside a Student is reached by chaining dots: s.joined.year. Build small types and compose them rather than writing one structure with twenty flat members.
The nesting also documents meaning. A Date type used in three places is defined once and understood everywhere.
Try it yourself
Define a Student structure, fill an array of three, and print the student with the highest marks.
Need a hint?
Track the index of the best student, not a copy of the structure.
Check the worked solution
Tracking the index rather than copying the structure keeps the loop cheap and means the name and marks printed at the end necessarily belong to the same student — the guarantee parallel arrays could not give. %-8s left-aligns the names into a readable column.
#include <stdio.h>
typedef struct {
int roll;
char name[40];
int marks;
} Student;
int main(void)
{
Student class[3] = {
{101, "Kavya", 87},
{102, "Ravi", 64},
{103, "Sneha", 91}
};
int best = 0;
for (int i = 1; i < 3; i++)
if (class[i].marks > class[best].marks)
best = i;
printf("Topper: %s (roll %d) with %d\n",
class[best].name, class[best].roll, class[best].marks);
return 0;
}Quick check
What advantage does an array of structures have over parallel arrays?
Why this lesson exists
Syllabus mapping
User-Defined Structure Types
Maps to course outcome CO5.