Array of Structures vs Array within a Structure in C++
Last Updated :
08 Feb, 2024
In C++, an array of structure and an array within structure are used frequently used for data storage. Although they sound similar, they work pretty differently from each other. In this article, we will discuss the key differences between an array of structures and an array within structures and clarify the confusion.
Array of Structures in C++
An array of structures combines both an array and a structure to handle complex data neatly. Instead of creating many separate variables of structure, we use an array of structures. Each element in this array is a structure on its own and since the array elements are stored continuously in memory, it allows for quick access and makes our program more efficient and straightforward.
Syntax
structName charArrayName[size];
We can also create a multidimensional array to store more structures.
Example
The below example demonstrates the use of an array of structures in C++.
C++
// C++ program to demonstrate the use of array of structure.
#include <cstring>
#include <iostream>
using namespace std;
// defining struct coordinates
struct Coordinates {
int x;
int y;
};
int main()
{
// Declare an array of structures
int size = 3;
Coordinates vertices[size];
// Assign values to elements in the array
vertices[0].x = 2;
vertices[0].y = 4;
vertices[1].x = 3;
vertices[1].y = 6;
vertices[2].x = 4;
vertices[2].y = 8;
// Displaying the values stored in the array of
// structures
for (int i = 0; i < size; ++i) {
cout << "Coordinates of ( x , y ) " << i + 1
<< ": (" << vertices[i].x << ", "
<< vertices[i].y << ")" << endl;
}
return 0;
}
OutputCoordinates of ( x , y ) 1: (2, 4)
Coordinates of ( x , y ) 2: (3, 6)
Coordinates of ( x , y ) 3: (4, 8)
Array Within a Structure in C++
An array within a structure simply means that we can create one or more arrays inside a structure as structure member which can be useful when we want to associate a collection of items within a single structure.
Syntax
structName myVar; // Creates a single variable of structName
Example
The below example demonstrates the use of an array within the structure.
C++
// C++ program to demonstrate the use of array within
// structure
#include <iostream>
#include <string>
using namespace std;
// Definingstructure
struct Student {
string name;
int grades[5]; // Array to store grades for 5 subjects
};
int main()
{
// Creating an instance of Student
Student student1;
// Initializing the student's name
student1.name = "Jack";
// Initializing the student's grades
student1.grades[0] = 85;
student1.grades[1] = 92;
student1.grades[2] = 76;
student1.grades[3] = 81;
student1.grades[4] = 90;
// Output the student's information
cout << "Student Name: " << student1.name << endl;
cout << "Grades: ";
for (int grade : student1.grades) {
cout << grade << " ";
}
cout << endl;
return 0;
}
OutputStudent Name: Jack
Grades: 85 92 76 81 90
Difference Between Array of Structures and Array Within a Structure in C++
The below table demonstrates the key differences between an array of structures and an array within structures:
Feature
| Array of Structures
| Array of Structures
|
---|
Definition
| It is declared as an array where each element is a structure.
| A structure contains an array as one of its members.
|
---|
Syntax
| struct Point { int x; int y; };
Point points[3];
| struct Person { char name[50];int grades[5]; };
Person person1;
|
---|
Memory Allocation
| Memory is allocated for every structure element separately.
| Memory is allocated for the entire structure, including the array within it.
|
---|
Memory Efficiency
| It can be a memory-saver if structures have a fixed size and minimal unused space.
| It may have higher memory overhead, especially if arrays within structures vary in size.
|
---|
Code Readability
| Enhances code readability by providing a clear structure for related data.
| Improves code readability by encapsulating arrays within the context of a single structure.
|
---|
Accessing Data
| Enhances code readability by providing a clear structure for related data.
| Accessing data involves indexing the structure and then the array within it.
|
---|
Conclusion
In conclusion, if you're dealing with many items that are alike and you want to work with them individually, go for an array of structures. But if you need to store multiple details about a single item, having an array within a structure will serve you better. Both ways help make your code more readable and organized, saving you time and effort when working with complex data.
Similar Reads
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Object Oriented Programming in C++ Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Inheritance in C++ The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
10 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read