Struct Array in C: Declaration and Usage

When you begin your journey in C programming, you learn how to store data using variables, arrays, and structures. Arrays are great when dealing with collections of similar data types. Structures, on the other hand, are perfect when you want to group different types of data. But what if you want to handle a collection of structures? That’s where an array of structures or struct array in C comes into play. This powerful concept is not only helpful in organizing data more efficiently but is also widely used in real-life applications.

Struct Array in C: Declaration and Usage

In this article, we will explore what struct arrays are, how to declare them, initialize them, and use them effectively in your C programs. Along the way, we will also understand where they fit in the bigger picture of structured programming. Let’s get started.

What Is a Structure in C?

Before we talk about struct arrays, let’s quickly revisit what a structure is in C.

structure is a user-defined data type that allows you to combine variables of different data types under one name. It is particularly useful when you want to represent an object or an entity with multiple attributes.

Example:

Copy Code

c

CopyEdit

struct Student {

    int rollNo;

    char name[50];

    float marks;

};

In this example, the Student structure groups together a student’s roll number, name, and marks. Each variable within the structure is called a member of the structure.

Now imagine if you have to handle details of 100 students. Defining 100 different variables is neither efficient nor practical. That’s where struct arrays come in.

What Is a Struct Array in C?

struct array or array of structures is simply an array where each element is a structure. It allows you to manage a list of records where each record has multiple pieces of data. It’s like having a spreadsheet where each row represents a student and columns represent roll number, name, and marks.

Syntax:

Copy Code

c

CopyEdit

struct StructureName arrayName[size];

Example:

Copy Code

c

CopyEdit

struct Student students[100];

In this case, students is an array of 100 elements, and each element is a Student structure.

Why Use Array of Structures?

You might wonder why not use separate arrays for roll numbers, names, and marks. Technically, that is possible, but it introduces complexity.

With struct arrays:

  • Data is organized
     
  • Each entity is treated as a unit
     
  • Code is more readable and maintainable
     
  • Easier to pass groups of data to functions
     

This becomes extremely helpful in real-world applications like employee records, library management systems, sales tracking, or even a simple program like sum of digits where structures can help manage both the number and its digit operations in a clean format.

How to Declare a Struct Array in C

Let’s walk through the steps of declaring and using a struct array in C programming.

Step 1: Define the Structure

Copy Code

c

CopyEdit

struct Book {

    int id;

    char title[100];

    float price;

};

Step 2: Declare an Array of Structures

Copy Code

c

CopyEdit

struct Book library[50];

This declares an array of 50 books. Each element of the array can store one book’s details.

How to Initialize Struct Arrays

There are two ways to initialize an array of structures:

1. Manual Initialization

Copy Code

c

CopyEdit

library[0].id = 101;

strcpy(library[0].title, "C Programming");

library[0].price = 350.50;

Use strcpy for string assignments, since direct assignment is not possible for character arrays.

2. Initialization at Declaration

Copy Code

c

CopyEdit

struct Book library[2] = {

    {101, "C Programming", 350.50},

    {102, "Data Structures", 420.75}

};

This is a more compact and readable way to initialize your struct array.

Accessing and Modifying Struct Array Elements

You can access members of a struct array using dot notation and array indexing.

Example:

Copy Code

c

CopyEdit

printf("Book Title: %s\n", library[1].title);

library[1].price = 400.00;

Just remember:

  • library[1] refers to the second book
     
  • .title or .price accesses a specific field

Input and Output for Struct Arrays

Let’s now write a complete example where we take input from the user and display data.

Program Example:

Copy Code

c

CopyEdit

#include <stdio.h>

#include <string.h>



struct Student {

    int rollNo;

    char name[50];

    float marks;

};



int main() {

    struct Student students[3];

    int i;



    // Input

    for(i = 0; i < 3; i++) {

        printf("Enter details of student %d\n", i + 1);

        printf("Roll No: ");

        scanf("%d", &students[i].rollNo);

        printf("Name: ");

        scanf(" %[^\n]", students[i].name); // to read spaces

        printf("Marks: ");

        scanf("%f", &students[i].marks);

    }



    // Output

    printf("\nStudent Records:\n");

    for(i = 0; i < 3; i++) {

        printf("Roll No: %d\n", students[i].rollNo);

        printf("Name: %s\n", students[i].name);

        printf("Marks: %.2f\n\n", students[i].marks);

    }



    return 0;

}



Output:

yaml

CopyEdit

Enter details of student 1

Roll No: 101

Name: Alice

Marks: 88.5



Enter details of student 2

Roll No: 102

Name: Bob

Marks: 92.0



Enter details of student 3

Roll No: 103

Name: Charlie

Marks: 79.4

Using Functions with Struct Arrays

You can also pass struct arrays to functions for better code organization.

Example: Function to Display Students with Marks > 80

Copy Code

c

CopyEdit

void displayTopStudents(struct Student s[], int n) {

    printf("Students scoring above 80:\n");

    for(int i = 0; i < n; i++) {

        if(s[i].marks > 80) {

            printf("%s\n", s[i].name);

        }

    }

}

You can call this function in your main program like this:

Copy Code

c

CopyEdit

displayTopStudents(students, 3);

Real World Example Using Struct Arrays

Let’s look at a real-world inspired example. Say, we want to track the total sales by different sales agents. You can use struct arrays to group data efficiently.

Copy Code

c

CopyEdit

struct SalesAgent {

    int id;

    char name[30];

    float salesAmount;

};

You can now calculate the total sales, average sales, top seller, and much more using simple iterations over this array.

Integration with Other Programs

You can even integrate struct arrays with simple programs like sum of digits to extend their functionality. For instance, consider a structure where you store a number and its digit sum:

Copy Code

c

CopyEdit

struct NumberData {

    int number;

    int sumOfDigits;

};

Now suppose you need to store and compute data for multiple numbers:

Copy Code

c

CopyEdit

for(int i = 0; i < 5; i++) {

    printf("Enter number: ");

    scanf("%d", &arr[i].number);

    int num = arr[i].number;

    int sum = 0;

    while(num != 0) {

        sum += num % 10;

        num /= 10;

    }

    arr[i].sumOfDigits = sum;

}

This type of usage demonstrates the flexibility and power of struct arrays in practical scenarios.

Tips for Using Struct Arrays Effectively

  1. Use meaningful structure names
    Keep your code clean and understandable by using relevant names like Employee, Student, Product, etc.
  2.  
  3. Group related data
    Only include fields in a structure that logically belong together.
     
  4. Keep array size manageable
    Avoid allocating more memory than necessary. Use dynamic memory if needed.
     
  5. Use functions to modularize code
    Separate input, processing, and output operations using functions that accept struct arrays.
     
  6. Remember scope and memory
    Arrays declared in functions are local. Use global or pointers carefully for larger programs.

Learn Struct Arrays and More With Uncodemy

If you are eager to learn how to write clean, efficient C code and understand how concepts like arrays, structures, and functions work together, consider exploring the C Programming Course offered by Uncodemy. Their industry-expert-led courses cover everything from basic syntax to complex topics like file handling, memory management, and struct arrays.

Uncodemy is known for offering practical, project-based training that prepares you for real-world coding challenges. Whether you're a student or a professional looking to upskill, their C programming module will help you master the language from the ground up.

Conclusion

Struct arrays in C are a fundamental yet powerful tool for managing structured data. They allow programmers to handle complex datasets efficiently while keeping the code readable and logical. Whether you are building a student record system, an inventory manager, or even something as small as a sum of digits tracker, struct arrays give you the flexibility to scale your logic.

By mastering struct arrays, you unlock the ability to build smarter and more organized programs that are not only functional but scalable. The more you practice, the more intuitive it becomes.

So go ahead and write your next C program using struct arrays. And if you're looking for structured guidance, do not forget to check out Uncodemy’s C Programming Course. Learn by doing, build real projects, and grow into a confident programmer.

Placed Students

Our Clients

Partners

...

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses