Open In App

How to Create an Array of Structs in C?

Last Updated : 11 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C, a structure is a user-defined data type that can be used to group items of different types into a single entity while an array is a collection of similar data elements. In this article, we will learn how to create an array of structs in C.

Creating an Array of Structs in C

To create an array of structs, we first need to define the struct type and then declare an array of that type using the below syntax.

Syntax to Create an Array of Structure in C

// Define the struct
struct StructName {
dataType1 member1;
dataType2 member2;
// more members...
};
// Declare an array of structs
struct StructName arrayName[arraySize];

Here,

  • StructName is the name of the struct.
  • dataType1dataType2 are the data types of the members of the struct.
  • member1member2 are the names of the members of the struct.
  • arrayName is the name of the array of structs.
  • arraySize is the size of the array.

C Program to Create an Array of Structs

The below program demonstrates how we can create an array of structs in C.

C




// C program to demonstrate how to create an array of
// structs
#include <stdio.h>
  
// Define the struct
struct Student {
    int id;
    char name[50];
};
  
int main()
{
    // Declare the size of the array
    int size = 5;
  
    // Declare an array of structs
    struct Student myArray[size];
  
    // Initialize data to structs present in the array
    for (int i = 0; i < size; i++) {
        myArray[i].id = i + 1;
        snprintf(myArray[i].name, sizeof(myArray[i].name),
                 "Student%d", i + 1);
    }
  
    // Print the data of structs present in the array
    printf("Array Elements:\n");
    for (int i = 0; i < size; i++) {
        printf("Element %d: ID = %d, Name = %s\n", i + 1,
               myArray[i].id, myArray[i].name);
    }
  
    return 0;
}


Output

Array Elements:
Element 1: ID = 1, Name = Student1
Element 2: ID = 2, Name = Student2
Element 3: ID = 3, Name = Student3
Element 4: ID = 4, Name = Student4
Element 5: ID = 5, Name = Student5

Time Complexity: O(N), here N is the number of elements present in the array
Auxiliary Space: O(N)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads