In C++, once a structure variable is defined we can access the member variables using member access operator(.) or dot operator. We cannot access members of a structure directly in any expression by specifying their name alone.
Syntax of accessing structure member using dot operator
struct employee { char name[100]; int age; float salary; char department[50]; } employee_one = {"Jack", 30, 1234.5, "Sales"}; int age = employee_one.age;
If you want to access age of structure variable employee_one and assign it 40 to it. You can do it as follows :
employee_one.age = 40;
Structure member variables are just like any other variable in C++. We can perform all valid input/output and arithmetic operations.
Accessing structure member using Arrow Operator(->)
If you have a pointer to a structure variable, then you cannot use dot operator to access it's member variable. C++ programming language provides a structure pointer operator(or Arrow operator) to access members of structure using pointer variable. Here is the syntax of accessing member variable using structure pointer.
Structure pointer variable followed by an arrow operator and then the name of the member variable.
For Example :struct employee { char name[100]; int age; float salary; char department[50]; } employee_one = {"Jack", 30, 1234.5, "Sales"}; struct employee *ptr = &employee_one; int age = ptr->age;
C++ Program to Access Structure Members Using Dot and Arrow Operator
#include <iostream> using namespace std; // Declaration of employee structure struct employee { char name[100]; int age; float salary; char department[50]; }; int main(){ struct employee EMP, *ptr; cout << "Enter Name, Age, Salary and Department of Employee\n"; // Assigning data to members of structure variable cin >> EMP.name >> EMP.age >> EMP.salary >> EMP.department; // Printing structure members using dot operator cout << "\nEmployee Details\n"; cout << "Name : " << EMP.name << "\nAge : "<< EMP.age << "\nSalary : "<< EMP.salary << "\nDepartment : "<< EMP.department; // Printing structure members using arrow operator ptr = &EMP; cout << "\n\nEmployee Details\n"; cout << "Name : " << ptr->name << "\nAge : "<< ptr->age << "\nSalary : "<< ptr->salary << "\nDepartment : "<< ptr->department; return 0; }
Program Output
Enter Name, Age, Salary and Department of Employee Andy 22 2345 SDE Employee Details Name : Andy Age : 22 Salary : 2345 Department : SDE Employee Details Name : Andy Age : 22 Salary : 2345 Department : SDE