Pointers to Structures in C++
C++ language – Pointers to Structures
In C++, a pointer is a variable that stores the memory address of another variable. A pointers to structures in C++ is a user-defined data type that consists of a collection of variables of different data types.You can use pointers to structures in C++ to reference the memory location of a structure variable.
Pointer to Structures in C++
Here is an example of how you might declare a structure and a pointer to it in C++:
struct Student { char name[30]; int age; float grade; }; struct Student *ptr;
To access the members of a structure using a pointer, you can use the “arrow” operator (->). For example:
ptr->name; // accesses the "name" member of the structure pointed to by "ptr" ptr->age; // accesses the "age" member of the structure pointed to by "ptr" ptr->grade; // accesses the "grade" member of the structure pointed to by "ptr"
You can also use the “dot” operator (.) to access the members of a structure, but this requires that you have the actual structure variable rather than just a pointer to it. For example:
struct Student s; s.name; // accesses the "name" member of the structure "s" s.age; // accesses the "age" member of the structure "s" s.grade; // accesses the "grade" member of the structure "s"
Pointers to structures can be useful when you want to pass a structure to a function by reference (i.e., modify the structure within the function) or when you want to create an array of structures and access the elements using pointers.
Pass a pointer to the structure:
#include <iostream> using namespace std; struct Employee { string name; int age; double salary; }; int main() { // create a Employee structure variable Employee e; // accessing the members of Employee structure e.name = "John"; e.age = 30; e.salary = 50000.0; // create a pointer to the Employee structure Employee *p_ptr = &e; // access the structure's members using the pointer cout << "Name: " << p_ptr->name << endl; cout << "Age: " << p_ptr->age << endl; cout << "Salary: " << p_ptr->salary << endl; cout<<endl; // assign values to the structure's members using the pointer p_ptr->name = "Sahil"; p_ptr->age = 35; p_ptr->salary = 55000.0; // access the structure's members using the pointer cout << "Name: " << e.name << endl; cout << "Age: " << e.age << endl; cout << "Salary: " << e.salary << endl; return 0; }
Output
Name: John Age: 30 Salary: 50000 Name: Sahil Age: 35 Salary: 55000In this example, we have created a pointer
p_ptr
to e
using the &
operator. The ->
operator is used to access the members of the structure through the pointer. Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment