Skip to content
StudyFame

Array of Structures in C

One structure variable holds one student. A class has 60 students. Making s1, s2, … s60 is the same mess arrays were invented to fix. The answer: an array of structures.

In this lesson you will build a small student record system: store many records, read them from the user, print a table, find the topper and sort students by marks. This is one of the most common C lab programs.

What You Will Learn

  • What an array of structures is.
  • How to declare and initialize it.
  • How to access arr[i].member.
  • How to read records from the user.
  • How to search, find the maximum and sort records.

What is an Array of Structures?

Exam definition: An array of structures is an array in which each element is a structure variable. A member of the i-th element is accessed as arr[i].member.

Memory trick: An array of structures is a class register. Each row is one student (a structure), and each column is one field (roll, name, marks). s[2].marks = "row 2, marks column".

struct student s[3];

         roll   name       marks
s[0]  :  101    "Asha"     88
s[1]  :  102    "Ravi"     72
s[2]  :  103    "Neha"     95        s[2].marks = 95
                                     s[1].name  = "Ravi"

Syntax of an Array of Structures

struct student
{
    int roll;
    char name[20];
    int marks;
};

struct student s[60];                        /* 60 records */

struct student t[3] = {                      /* initialize */
    {101, "Asha", 88},
    {102, "Ravi", 72},
    {103, "Neha", 95}
};

t[1].marks = 75;                             /* access */
printf("%s", t[2].name);

Example 1: Read and Print Student Records

#include <stdio.h>

struct student
{
    int roll;
    char name[20];
    int marks;
};

int main(void)
{
    struct student s[50];
    int n, i;

    printf("How many students? ");
    scanf("%d", &n);

    for (i = 0; i < n; i++)
    {
        printf("Roll, name, marks of student %d: ", i + 1);
        scanf("%d %19s %d", &s[i].roll, s[i].name, &s[i].marks);
    }

    printf("\n%-6s %-10s %s\n", "Roll", "Name", "Marks");
    for (i = 0; i < n; i++)
        printf("%-6d %-10s %d\n", s[i].roll, s[i].name, s[i].marks);

    return 0;
}

Output

How many students? 3
Roll, name, marks of student 1: 101 Asha 88
Roll, name, marks of student 2: 102 Ravi 72
Roll, name, marks of student 3: 103 Neha 95

Roll   Name       Marks
101    Asha       88
102    Ravi       72
103    Neha       95

Code Explanation

  1. struct student s[50]; reserves space for 50 records. We use the first n.
  2. &s[i].roll: the dot binds before &, so this is the address of s[i]'s roll. It's what scanf needs.
  3. s[i].name is a char array, so it needs no &.
  4. %-6d and %-10s left-align values in fixed widths, so the table lines up.

How Searching and Sorting Records Works

  • Find the topper: keep the index of the best record so far, like finding the largest number.
  • Search by roll: loop and compare s[i].roll == key.
  • Sort by marks: bubble sort comparing s[j].marks, but swap the whole structure. Because structures can be assigned with =, the swap needs no strcpy:
struct student temp = s[j];
s[j] = s[j + 1];
s[j + 1] = temp;

Example 2: Topper, Average and Sorting by Marks

#include <stdio.h>

struct student
{
    int roll;
    char name[20];
    int marks;
};

int main(void)
{
    struct student s[] = {
        {101, "Asha", 88}, {102, "Ravi", 72}, {103, "Neha", 95},
        {104, "Arjun", 64}, {105, "Meera", 81}
    };
    int n = sizeof(s) / sizeof(s[0]);
    int i, j, top = 0, total = 0;
    struct student temp;

    for (i = 0; i < n; i++)
    {
        total += s[i].marks;
        if (s[i].marks > s[top].marks)
            top = i;
    }
    printf("Topper : %s (%d)\n", s[top].name, s[top].marks);
    printf("Average: %.1f\n", (float) total / n);

    /* sort by marks, highest first */
    for (i = 0; i < n - 1; i++)
        for (j = 0; j < n - 1 - i; j++)
            if (s[j].marks < s[j + 1].marks)
            {
                temp = s[j];              /* swap whole records */
                s[j] = s[j + 1];
                s[j + 1] = temp;
            }

    printf("Rank list:\n");
    for (i = 0; i < n; i++)
        printf("%d. %-6s %d\n", i + 1, s[i].name, s[i].marks);

    return 0;
}

Output

Topper : Neha (95)
Average: 80.0
Rank list:
1. Neha   95
2. Asha   88
3. Meera  81
4. Ravi   72
5. Arjun  64
  • sizeof(s) / sizeof(s[0]) counts records, just like with any array.
  • Swapping whole structures keeps each student's roll, name and marks together. Sorting only the marks would mix up the data.
  • To sort by name instead, compare with strcmp(s[j].name, s[j+1].name) > 0.

Important Points to Remember

  • Each element of the array is a whole structure.
  • Access members as arr[i].member.
  • In scanf: &s[i].roll for numbers, s[i].name (no &) for strings.
  • Records can be swapped with = while sorting.
  • Track the index of the best record to print all its details.
  • Initialize with nested braces: { {..}, {..} }.

Common Mistakes Beginners Make

MistakeWhat happensFix
s.marks[i] instead of s[i].marksCompile errorIndex the array, then the member
scanf("%d", s[i].roll)Crash: value passed, not address&s[i].roll
Swapping only the marks while sortingNames and marks get mixed upSwap the whole structure
Reading a name with spaces using %sOnly the first word is storedUse fgets (clear the buffer first)
Storing the topper's marks, not indexCan't print the topper's nameKeep the index

Array of Structures Practice Questions

  1. Declare an array to hold 100 records of struct book.
  2. How do you access the price of the 5th book?
  3. Why is & used with s[i].roll but not with s[i].name in scanf?
  4. Why should we swap the whole structure while sorting?
  5. How many bytes does struct point p[10] use if one struct point is 8 bytes?
Show answers
  1. struct book b[100];
  2. b[4].price.
  3. roll is an int (scanf needs its address); name is a char array whose name is already an address.
  4. So all fields of a record stay together.
  5. 80 bytes.

Coding Exercise

Using the 5 students from Example 2, print the names of students who scored above the class average, and search for roll number 104.

Show solution
#include <stdio.h>

struct student { int roll; char name[20]; int marks; };

int main(void)
{
    struct student s[] = {
        {101, "Asha", 88}, {102, "Ravi", 72}, {103, "Neha", 95},
        {104, "Arjun", 64}, {105, "Meera", 81}
    };
    int n = 5, i, total = 0, key = 104;
    float avg;

    for (i = 0; i < n; i++)
        total += s[i].marks;
    avg = (float) total / n;

    printf("Above average (%.1f):", avg);
    for (i = 0; i < n; i++)
        if (s[i].marks > avg)
            printf(" %s", s[i].name);
    printf("\n");

    for (i = 0; i < n; i++)
        if (s[i].roll == key)
            printf("Roll %d: %s, %d marks\n", key, s[i].name, s[i].marks);
    return 0;
}
Above average (80.0): Asha Neha Meera
Roll 104: Arjun, 64 marks

Quick Quiz: Array of Structures (MCQ)

  1. Correct way to access marks of the 3rd student:

    A) s.marks[2]   B) s[2].marks   C) s[3].marks   D) marks.s[2]

  2. Which scanf argument is correct for an int member?

    A) s[i].roll   B) &s[i].roll   C) *s[i].roll   D) &s.roll[i]

  3. Two records a and b of the same struct type can be swapped using:

    A) strcpy only   B) A temp struct and =   C) memcmp   D) Not possible

  4. Each element of struct student s[10] is:

    A) An int   B) A pointer   C) A struct student   D) A string

  5. Number of records in s is:

    A) sizeof(s)   B) sizeof(s) / sizeof(s[0])   C) strlen(s)   D) sizeof(s[0])

Show answers
  1. B: s[2].marks.
  2. B: &s[i].roll.
  3. B: a temp struct and =.
  4. C: a struct student.
  5. B: sizeof(s) / sizeof(s[0]).

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

Array of structuresEach element is a struct
Accessarr[i].member
scanf int member&s[i].roll
scanf string members[i].name (no &)
Sorting recordsSwap whole struct with =
Count recordssizeof(s) / sizeof(s[0])

Frequently asked questions

What is an array of structures?
An array whose every element is a structure, used to store many records of the same kind.
How do you sort an array of structures?
Compare a member (like marks) and swap the whole structures using a temp variable.
How do you find the topper in an array of structures?
Keep the index of the highest marks while looping, then print that record.

Remember

  • Array of structures = class register: rows are students.
  • Index first, then dot: s[i].marks.

Next Topic

Next lesson: Nested Structures in C. You will put one structure inside another, like a date inside a student record.