In the C/C++ programming language, the structure is user-defined data types that allow us to store the combination of different data types together. All the different data type variables are represented by a single name.
Unlike an array that holds the data of the same type, the structure holds the data of different types in a contiguous memory location. It begins with the keyword struct
.
Suppose, we want to keep the record of students with their name(string), roll_no(int), address(string), Score(float) and these are of different data types. So instead of creating a different variable, again and again, we can simply create members for each student with their respective data.
Syntax of struct in C++:
The keyword used to define the structure is struct
.
1 2 3 4 5 6 7 8 | struct structure_name { data_type member1; data_type member2; data_type member3; ... ... }; |
Consider basic data of student: name, roll_no, score.
student structure is declared in the following way:
1 2 3 4 5 6 | struct student { char name[30]; int roll_no; float score; }; |
Declaring Structure variable
It means creating an instance of a structure in order to access the members of the structure. Once the structure student
is declared, its variable is created by adding the following in the main function.
struct student s1, s2;
s1
and s2
are structure variables of the type Student
. These are like the objects for the student just like an object in C++. When these variables are created, memory is allocated by the compiler.
Accessing Struct Members
The structure variable can be accessed by using a dot (.) operator.
Suppose you want to access the score of an s1
student and assign it with a value of 80. This work can be performed in the following way.
s1.score = 80;
Example of C++ Structure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | #include <iostream> #include <cstring> using namespace std; struct Student { char name[50]; int roll; float score; }; int main() { Student s1, s2; //Accessing Student members strcpy(s1.name, "John Mac"); s1.roll = 101; s1.score = 92.15; strcpy(s2.name, "Mickey Macguel"); s2.roll = 102; s2.score = 80; //Display student 1 Info cout << "Student 1 Information" <<endl; cout << "Name: " << s1.name <<endl; cout << "Roll No: " << s1.roll <<endl; cout << "Score: " << s1.score <<endl <<endl; //Display student 2 Info cout << "Student 2 Information" <<endl; cout << "Name: " << s2.name <<endl; cout << "Roll No: " << s2.roll <<endl; cout << "Score: " << s2.score <<endl; return 0; } |
Output:
Student 1 Information
Name: John Mac
Roll No: 101
Score: 92.15
Student 2 Information
Name: Mickey Macguel
Roll No: 102
Score: 80
After learning structure, go through the following topics in structure: