Array of Structure in C Programming

In this tutorial, we will learn about array of structure variables in c programming language. Declaration of structure array and accessing structure array element using subscript.


A structure in C programming language is used to store set of parameters about an object/entity. We sometime want to store multiple such structure variables for hundreds or objects then Array of Structure is used.

Both structure variables and in-built data type gets same treatment in C programming language. C language allows us to create an array of structure variable like we create array of integers or floating point value. The syntax of declaring an array of structure, accessing individual array elements and array indexing is same as any in-built data type array.


Declaration of Structure Array in C

struct Employee {
    char name[50];
    int age;
    float salary;
}employees[1000];
or
struct Employee employees[1000];

In above declaration, we are declaring an array of 1000 employees where each employee structure contains name, age and salary members. Array employees[0] stores the information of 1st employee, employees[1] stores the information of 2nd employee and so on.

Accessing Structure Fields in Array

We can access individual members of a structure variable as

array_name[index].member_name
For Example
employees[5].age

C Program to Show the Use of Array of Structures

In below program, we are declaring a structure "employee" to store details of an employee like name, age and salary. Then we declare an array of structure employee named "employees" of size 10, to store details of multiple employees.

#include <stdio.h>

struct employee {
 char name[100];
 int age;
 float salary;
};

int main(){
   struct employee employees[10];
   int counter, index, count, totalSalary;
   
   printf("Enter Number of Employees\n");
   scanf("%d", &count);
   
   /* Storing employee detaisl in structure array */
   for(counter=0; counter<count; counter++){ 
       printf("Enter Name, Age and Salary of Employee\n");
       scanf("%s %d %f", &employees[counter].name, 
           &employees[counter].age, &employees[counter].salary);
   }
   
   /* Calculating average salary of an employee */
   for(totalSalary=0, index=0; index<count; index++){
       totalSalary += employees[index].salary;
   }
   
   printf("Average Salary of an Employee is %f\n", 
       (float)totalSalary/count);

   return 0;
}

Output
Enter Number of Employees
3
Enter Name, Age and Salary of Employee
Jack 30 100
Enter Name, Age and Salary of Employee
Mike 32 200
Enter Name, Age and Salary of Employee
Nick 40 300
Average Salary of an Employee is 200.000000

Pointers to Structure in C

The pointers to a structure in C in very similar to the pointer to any in-built data type variable.

The syntax for declaring a pointer to structure variable is as follows:

struct structure_name *pointer_variable
For Example
struct Employee
{
    char name[50];
    int age;
    float salary;
}employee_one;
struct Employee *employee_ptr;
We can use addressOf operator(&) to get the address of structure variable.
struct Employee *employee_ptr = &employee_one;

To access the member variable using a pointer to a structure variable we can use arrow operator(->). We can access member variable by using pointer variable followed by an arrow operator and then the name of the member variable.

To access a member variable of structure using variable identifier we use dot(.) operator whereas we use arrow(->) operator to access member variable using structure pointer.

employee_ptr->salary;


C Program to print the members of a structure using Pointer and Arrow Operators

#include <stdio.h>

struct employee {
 char name[100];
 int age;
 float salary;
 char department[50];
};

int main(){
   struct employee employee_one, *ptr;
   
   printf("Enter Name, Age, Salary and Department of Employee\n");
   scanf("%s %d %f %s", &employee_one.name, &employee_one.age,
       &employee_one.salary, &employee_one.department);

       
   /* Printing structure members using arrow operator */
   ptr = &employee_one;
   printf("\nEmployee Details\n");
   printf(" Name : %s\n Age : %d\n Salary = %f\n Dept : %s\n", 
       ptr->name, ptr->age, ptr->salary, ptr->department);

   return 0;
}
Output
Enter Name, Age, Salary and Department of Employee
Jack 30 1234.5 Sales
 
Employee Details
 Name : Jack
 Age : 30
 Salary = 1234.500000
 Dept : Sales

Best Practices of Working with Pointers to Structures in C

When working with pointers to structures in C, it's crucial to follow best practices to ensure code correctness, maintainability, and readability. Here are some best practices for using pointers to structures in C:
  • Initialization and Allocation : Always initialize pointers to structures before use. Use dynamic memory allocation functions like malloc or calloc when needed.
    struct MyStruct* myStructPtr = malloc(sizeof(struct MyStruct));
    

  • Null Checking : Check if the pointer is NULL before accessing or manipulating the structure to avoid segmentation faults.
    if (myStructPtr != NULL) {
        // Access or modify the structure
    }
    

  • Pointer Arithmetic : Use pointer arithmetic cautiously, ensuring that it stays within the bounds of the allocated memory for the structure.
    myStructPtr++; // Be mindful of the structure size
    

  • Avoiding Dangling Pointers : Ensure that pointers to structures do not point to deallocated memory. Set the pointer to NULL after freeing the memory.
    free(myStructPtr);
    myStructPtr = NULL;
    

  • Passing Pointers to Functions : Pass pointers to structures to functions when modifying the original structure is required. Use const appropriately to indicate read-only access.
    void modifyStruct(struct MyStruct* ptr) {
        // Modify the structure through the pointer
    }
    
  • By adhering to these best practices, developers can write robust and maintainable code when using pointers to structures in C. These practices help prevent common issues such as memory leaks, segmentation faults, and undefined behavior, leading to more reliable and readable code.

Conclusion

Manipulating data structures in the C programming language involves leveraging the potency of the array of structures. This amalgamation seamlessly integrates the adaptable nature of arrays with the methodical organization intrinsic to user-defined types. The result is the formulation of code that is not only effective but also eminently readable when confronted with multifarious datasets.

As you progress along your trajectory in C programming, keep in mind that becoming adept at handling data structures such as the array of structures extends beyond the realm of mere code composition. It entails the crafting of sophisticated solutions for tangible predicaments encountered in the actual world. Engage in deliberate practice, exploring diverse scenarios to fortify your comprehension. Before long, you'll effortlessly navigate the intricacies of arrays and structures within the C programming domain.