Open In App

How to Access Array of Structure in C?

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C, we can create an array whose elements are of struct type. In this article, we will learn how to access an array of structures in C.

For Example,

Input:
myArrayOfStructs = {{'a', 10}, {'b', 20}, {'A', 9}}
Output:
Integer Member at index 1: 20

Accessing Array of Structure Members in C

We can access the array of structures in a very similar to accessing array elements. To access members of an array of structures we can use the array indexing and access individual fields of a struct using the dot operator.

Syntax to Access Array of Structure in C

arrayName[index].member;

Here,

  • arrayName is the name of the array of struct.
  • index is the position of the struct in the array that we want to access, starting from 0.
  • member is the name of the member within the struct that we want to access.

C Program to Access Array of Struct Members

The below program demonstrates how we can access an array of structures in C.

C




// C Program to access the members of array of structure
#include <stdio.h>
  
// Defining the struct
struct MyStruct {
    int id;
    char name[20];
};
  
int main()
{
    // Declaring an array of structs
    struct MyStruct myArray[] = {
        { 1, "Person1" },
        { 2, "Person2" },
    };
  
    // Accessing and printing data using array indexing
    printf("Struct at index 0: ID = %d, Name = %s\n",
           myArray[0].id, myArray[0].name);
  
    // Modifying the id of the second person
    myArray[1].id = 3;
  
    // Accessing and printing the updated information of the
    // second person
    printf("Struct at index 1 after modifying: ID = %d, "
           "Name = %s\n",
           myArray[1].id, myArray[1].name);
  
    return 0;
}


Output

Struct at index 0: ID = 1, Name = Person1
Struct at index 1 after modifying: ID = 3, Name = Person2

Time Complexity: O(1)
Space Complexity: O(1)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads