How to Create an Array of Structs in C++?
Last Updated : 11 Mar, 2024
Improve
In C++, a struct is a user-defined data type that allows us to combine data of different types and an array of structs is an array in which each element is of the struct type. 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 struct using the below syntax.
Syntax to Create an Array of Structs in C++
// Define the struct
struct StructName {
dataType1 member1;
dataType2 member2;
// more members...
};
// Declare an array of structs
StructName arrayName[arraySize];
Here,
StructName
is the name of the struct.dataType1
,dataType2
are the data types of the members of the struct.member1
,member2
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++ program to illustrate how to create an array of
// structs
#include <iostream>
#include <string>
using namespace std;
// Defining the struct
struct Student {
int id;
string name;
};
int main()
{
// Declaring the size of the array
int size = 3;
// Declaring an array of structs
Student myArray[size];
// Initializing data to structs present in the array
for (int i = 0; i < size; i++) {
myArray[i].id = i + 1;
myArray[i].name = "Student" + to_string(i + 1);
}
// Printing the data of structs present in the array
cout << "Array Elements:" << endl;
for (int i = 0; i < size; i++) {
cout << "Element " << i + 1
<< ": ID = " << myArray[i].id
<< ", Name = " << myArray[i].name << endl;
}
return 0;
}
Output
Array Elements: Element 1: ID = 1, Name = Student1 Element 2: ID = 2, Name = Student2 Element 3: ID = 3, Name = Student3
Time Complexity: O(N), here N is the number of elements present in the array.
Auxiliary Space: O(N)