Structures in C++

Filed Under: C++
Structures In C++

Introduction

In this tutorial, we are going to learn the basics of Structures in C++, their working, as well as their uses. C++ offers custom data types that can be created by the user using various methods or techniques. The structure is one of them. Understanding structures play a vital role in paving the path to use classes and objects in C++.

What are Structures in C++?

Structures are the grouping of various variables in the same name. In some cases, we need to put logically related elements together and treat them under one unit.

This issue can be solved by incorporating structures. A structure can be declared in C++ using the struct keyword. The syntax for the same is given below,

struct structure_name
{
    data_type1 ele1;
    ...
    data_typeN eleN;
}structure_variable,...;

Here,

  • struct keyword is used to initialize a structure structure_name,
  • The structure contains various elements of different data types or similar one named ele1, …, up to eleN,
  • structure_variable, as the name suggests, is a variable of the custom data type structure_name. Note: we can declare multiple structure variables by separating them with commas(‘,’).

Remember, we can also declare a structure variable after structure declaration in using the code snippet given below,

structure_name variable_name;

Structure Elements

Let us consider a structure named date to understand structure elements in C++.

#include<iostream>
using namespace std;
struct date{   //declared date structure
    int dd;          //day
    int mm;          //month
    int yyyy;        //year
}birthday;  //variable birthday

int main()
{
	birthday.dd=1;     //initialisation of structure elements
	birthday.mm=1;
	birthday.yyyy=2001;
	cout<<"Birthday is on: "<<birthday.dd<<"/"<<birthday.mm<<"/"<<birthday.yyyy;  //accessing elements using . operator
	return 0;
}

Output:

Birthday is on: 1/1/2001

So in the code above,

  • We have declared a structure, date having elements dd, mm, and yyyy, storing corresponding date,
  • Inside the main() function we initialise the respective dd, mm, and yyyy elements of the structure variable birthday. This was done by accessing a particular element from the structure variable using the ‘.’ operator,
  • Further, we print the whole birthday again using the dot(‘.‘) operator and get the desired output.

Hence in this way, we can initialise as well as access the different elements of a structure. Try it yourself to get a better understanding.

Nested Structures in C++

A structure element may be simple or complex. It may consist of an element that is itself a complex one i.e., structure or arrays etc. A structure consisting of such elements is known as a complex structure. And if the structure has another structure as one of its elements, then we refer to the set as a Nested structure. Look at the example below,

#include<iostream>
using namespace std;
struct Addr{
	char area[20];
	char state[20];
	char country[20];
};
struct stud{             //stud structure declaration
	int roll;
	char name[30];
	Addr address;   //address is another structure variable of type Addr
};

int main() {
stud s1; //Declaring the object
}

As you can clearly see, here stud is a structure consisting of another structure variable address of type Addr. This is how nested structures look like in C++. Accessing nested structure elements is going to be discussed in the next section.

Accessing Nested Structure Members

In case you want to access the members of the nested structure, you can use the dot(‘.’)operator further to do so. For example, if we need to access the country element from the address variable from the above code, we can use the following snippet:

stud s1.address.country;

Again, we can initialize all the nested structure elements all together in the following way:

stud s2={ 10,"John",{ "Garia", "Kolkata", "India"} };

Here, we declare another structure variable of data type stud named s2 as well as initialize the same with some values.

Let’s use the code snippet from the above section and access the nested variables:

#include<iostream>
using namespace std;
struct Addr{
	char area[20];
	char state[20];
	char country[20];
};
struct stud{             //stud structure declaration
	int roll;
	char name[30];
	Addr address;   //address is another structure variable of type Addr
};

int main() {
stud s1={ 10,"John",{ "Garia", "Kolkata", "India"} }; //Declaring Variable

cout<<s1.name<<"\n";
cout<<s1.address.area<<"\n";
cout<<s1.address.state<<"\n";
cout<<s1.address.country<<"\n";
return 0;
}

In this way, we can print as well as initialize the nested elements.

Array of Structures in C++

We know arrays contain a series of similar type elements. So, an array of structures is an array comprising of only structure type elements.

The declaration for an Array of structure type elements is similar to that of a structure type variable. Just we need to specify the size of the array. Look at the example below,

struct Addr{
	char area[20];
	char state[20];
	char country[20];
};
Addr Add[10];
  • So for the above example, Addr is a structure with 3 elements- area, state, and country.
  • We declare an array member of the type structure Addr, named Add with a size 10.
  • This means, the array Add[10] can now store 10 structure type variables or more specifically, 10 addresses.

For accessing individual elements of the array we can again use the ‘.’ operator, but this time we need to mention the array index to do so. Let us see how

Addr.Add[i].area

In this way, we access the area for the structure element present at the ith position in the array, Add[].

Passing Structures to Functions

Until now we used global structures. But in many cases, we may need to pass a structure or its elements to a function for performing any operations on them and return some value in some cases. This can be achieved by passing the following as parameters to the function,

  • Structure Elements to Functions
  • Structure to Functions
  • An array of Structures to Functions

So, now let us dig deep into each one of the methods using some easy examples.

1. Passing Structure Elements to Functions

We can pass all the elements of a structure to a function by making them receive the values by creating its own copy for them( call by value ) and operate accordingly. Therefore, in the example below,

struct stud{
	int roll;
	char name[30];
	int marks[5];
};
stud s1;

we can directly pass the elements to a function by call-by-value method as shown below,

Function(s1.roll, s1.name, s1.marks);

For the above example, the function makes its own copies for the individual elements and now can operate on them without changing the values in the actual address.

2. Passing Structure to Functions

Look at the example below, here we try to pass an entire structure to a function and work accordingly.

#include<iostream>
using namespace std;

struct stud{
	int roll;
	char name[30];
	int marks[5];
};
//function accepts the address of the structure s1 in a pointer type //variable s
void prnt(stud *s) 
{
	cout<<"\nStudent Details are printed below:\n";
	cout<<"Name : "<<s->name;
	cout<<"\nroll : "<<s->roll;
	cout<<"\nMarks for 5 subjects : ";
	for(int i=0;i<5;i++)
	{
		cout<<"\t"<<s->marks[i];
	}
}

int main()
{
	int i;
        stud s1; //structure variable declared
	cout<<"\nEnter student name : ";
	gets(s1.name);
	cout<<"\nEnter roll : ";
	cin>>s1.roll;
	cout<<"\n Enter 5 subject marks : ";
	for(i=0;i<5;i++)
	{
		cin>>s1.marks[i];
	}
	prnt(&s1);   //Address of the structure s1 is passed as parameter
	return 0;
}

Output:

Passing Structure To Function
Passing Structure To Function

Understand the code:

  • Here in this program, we declared a structure, stud with 3 elements- name, roll and marks for 5 subjects.
  • Inside the main() function, we first took the user input and stored the same inside the structure variable s1,
  • After doing so we call the function prnt() with the address of s1 as the parameter,
  • Accordingly, the function stores the address in a pointer ‘s’. Further, we use this pointer to access the various elements of the structure s1 and print the same.

Notice that we use the ‘->’ operator while accessing the elements of s1 through the pointer s. This operator is used to access such elements using a pointer to the specific structure.

3. Passing Array of Structures to Functions

Similar to passing structure variable to a function in C++, the language also allows us to pass an array of structures. The code below illustrates the procedure of doing so,

#include<iostream>
using namespace std;

struct stud{
	int roll;
	char name[30];
	int marks[3];
};

stud s1[2];  //array of type stud declared with size 2
//function accepts the address of the structure s1 in a pointer type //variable s
void prnt(stud *s)       
{
	cout<<"\nStudent Details are printed below:\n";
	for(int i=0;i<2;i++)
	{
		cout<<"\nName for student "<<i<<" : "<<s[i].name;
		cout<<"\nRoll for student "<<i<<" : "<<s[i].roll;
		cout<<"\nMarks for student "<<i<<" : ";
		for(int j=0;j<3;j++)
		{
			cout<<"\t"<<s[i].marks[j];
		}
	}
}

int main()
{
	int i,j;
	cout<<"Enter Student details here ::::";
	for(i=0;i<2;i++)
	{
		cout<<"\nEnter student name for student "<<i<<" : ";
		fflush(stdin); //used to avoid buffer error for using gets()
		gets(s1[i].name);
		cout<<"\nEnter roll for student "<<i<<" : ";
		cin>>s1[i].roll;
		cout<<"\n Enter 5 subject marks for student "<<i<<" : ";
		for(j=0;j<3;j++)
		{
			cin>>s1[i].marks[j];
		}
	}
	prnt(s1);   //Address of the structure s1 is passed as parameter
	return 0;
}

Output:

Passing Array Of Structures
Passing Array Of Structures

Understand the code,

  • Here in this program, we have used the same structure type stud consisting of 3 elements,
  • But this time we have declared an array of structures of type stud with size 2. This time we are to store the various data for 2 students in this array and print the same,
  • Similar to the previous example here we take the user input for the student details using a for loop for 2 students,
  • After we are done taking input we call the prnt() function with s1 as the parameter. Remember for an array, its name serves as the base address too? Hence, here we use the same property to pass the address of the array of structures, s1,
  • The prnt() function takes in the address of the array inside a pointer, s.
  • Inside the prnt() function, we print the student details for both the students by accessing the elements as shown above using a for loop again.

Did you notice, this time while accessing the elements of the structure, we didn’t use the ‘->’ operator, instead used the old ‘.’ one. This is because of the fact that s[i] is not a pointer, it is actually the value *( s + i ) or, s1[ i ].

Returning Structures by Functions

Like other types, functions can return structures too. Then the return type of the function should be the same as that of the structure. For example, if we want a function to return a structure of type stud for the above code, we must declare the function as:

stud func( stud s1, stud s2 )
{
    stud s3;
    statements...;
    return s3;
}

Here,

  • Both s1 and s2 are structure variables of type stud,
  • Here, func() is a function with return type stud. It returns another structure s3 of type stud where it was initially called.

Conclusion

So, in this tutorial, we learned about the structures in C++ in details as well as how we can implement the same in C++ using different techniques.

References

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages