In C++, the pointers to a structure variable in very similar to the pointer to any in-built data type variable. A pointer to a structure in C++ is a variable that stores the memory address of a structure. This combination allows for dynamic memory allocation, efficient data manipulation, and provides a mechanism for working with complex data structures.
Syntax for declaring a pointer to structure variablestruct Employee { char name[50]; int age; float salary; }employee_one; struct Employee *employee_ptr;
To get the address of a structure variable, we can use addressOf operator(&).
struct Employee *employee_ptr = &employee_one;
To access the member variable using a pointer, we can use arrow operator(->). We can access member variable by using pointer followed by an arrow operator and then the name of the member variable.
employee_ptr->salary;
C++ Pointer to Structure Example Program
#include <iostream> using namespace std; struct employee { char name[100]; int age; float salary; char department[50]; }; int main(){ struct employee manager, *ptr; printf("Enter Name, Age, Salary and Department of Employee\n"); // Assigning data to members of structure variable cin >> manager.name >> manager.age >> manager.salary >> manager.department; /* Printing structure members using arrow operator */ ptr = &manager; cout << "\nEmployee Details\n"; cout << "Name : " << ptr->name << "\nAge : "<< ptr->age << "\nSalary : " << ptr->salary << "\nDepartment : "<< ptr->department; return 0; }
Output
Enter Name, Age, Salary and Department of Employee Dan 42 8453 Accounting Employee Details Name : Aman Age : 42 Salary : 8453 Department : Accounting
Dynamic Memory Allocation for Structures
Pointers to structures are often used with dynamic memory allocation to create structures at runtime. This flexibility allows for efficient memory usage and dynamic data manipulation.
#include <iostream> // Declaration of a structure named 'Rectangle' struct Rectangle { double length; double width; }; int main() { // Declaration of a pointer to the 'Rectangle' structure Rectangle* rectanglePtr; // Dynamic memory allocation for a 'Rectangle' structure rectanglePtr = new Rectangle; // Assigning values to structure members using the pointer rectanglePtr->length = 5.0; rectanglePtr->width = 3.0; // Displaying structure information using the pointer std::cout << "Length: " << rectanglePtr->length << std::endl; std::cout << "Width: " << rectanglePtr->width << std::endl; // Don't forget to free the allocated memory delete rectanglePtr; return 0; }Here, rectanglePtr is a pointer to the dynamically allocated Rectangle structure. The new keyword is used to allocate memory, and delete is used to free the memory when it's no longer needed.
Passing Structure to Function in C++
In C++, we can pass a structure variable to a function as argument like we pass any other variable to a function. Structure variable is passed using call by value. To take a structure variable as argument, function must declare a structure argument in it's declaration. Any change in the value of formal parameter inside function body, will not affect the value of actual parameter.
For Example :struct employee { char name[100]; int age; float salary; char department[50]; }; void printEmployeeDetails(struct employee emp);
We can also pass address of a structure to a function. In this case, any change in the formal parameter inside function's body will reflect in actual parameter also. To take a structure pointer as parameter a function declare a a structure pointer as it's formal parameter.
void printEmployeeDetails(struct employee *emp);Like any other inbuilt data type, we can also pass individual member of a structure as function argument.
C++ Program to Pass Structure Variable to a Function
#include <iostream> using namespace std; struct employee { char name[100]; int age; float salary; char department[50]; }; // This function takes structure variable as parameter void printEmployeeDetails(struct employee emp){ cout << "\n*** Employee Details ***\n"; cout << "Name : " << emp.name << "\nAge : "<< emp.age << "\nSalary : " << emp.salary << "\nDepartment : "<< emp.department; } // This function takes structure pointer as parameter void printEmployeeDetails(struct employee *emp){ cout << "\n--- Employee Details ---\n"; cout << "Name : " << emp->name << "\nAge : "<< emp->age << "\nSalary : " << emp->salary << "\nDepartment : "<< emp->department; } void printAge(int age){ cout << "\n\nAge = " << age; } int main(){ struct employee manager, *ptr; printf("Enter Name, Age, Salary and Department of Employee\n"); // Assigning data to members of structure variable cin >> manager.name >> manager.age >> manager.salary >> manager.department; // Passing structure variable to function printEmployeeDetails(manager); // Passing address of structure variable to a function printEmployeeDetails(&manager); /* Passing structure member to function */ printAge(manager.age); return 0; }Output
Enter Name, Age, Salary and Department of Employee David 32 98765 SDE *** Employee Details *** Name : David Age : 32 Salary : 98765 Department : SDE --- Employee Details --- Name : David Age : 32 Salary : 98765 Department : SDE Age = 32
Best Practices of Using Pointers with Structures in C++
- Initialization and Allocation : Always initialize pointers to structures before use to avoid accessing uninitialized memory. Use dynamic memory allocation (e.g., new keyword) when creating structures dynamically.
// Example initialization and allocation MyStruct* ptr = nullptr; // Initialize to nullptr ptr = new MyStruct; // Allocate memory dynamically
- Memory Deallocation : When using dynamic allocation, remember to free the memory using delete to prevent memory leaks.
// Example deallocation delete ptr; // Free allocated memory
- Null Pointer Checks : Always check if a pointer is nullptr before dereferencing it to avoid segmentation faults.
// Example null pointer check if (ptr != nullptr) { // Dereferencing safely ptr->member = value; }
- Documentation : Clearly document the ownership and lifetime responsibilities when passing pointers to structures, especially in function interfaces.
// Example documentation void processStruct(const MyStruct* data);
Benefits of Utilizing Pointers with Structures
- Optimized Memory Usage : Leveraging pointers enhances the efficiency of memory utilization, particularly when managing extensive structures. Instead of transferring the entire structure, you transmit the memory address, diminishing the overhead associated with data duplication.
- Facilitates Direct Control : Pointers furnish a straightforward means to manage structure members directly. This proves advantageous, especially when confronted with dynamic memory allocation or the need to modify structure elements within functions.
Conclusion
In this tutorial, we've explored the use of pointers with structures in C++. Understanding how to create pointers to structures and pass structures to functions is crucial for efficient and modular programming. By leveraging these concepts, you can write more dynamic and memory-efficient C++ code.
Don't forget to reinforce your understanding by engaging in practical exercises. As you progress further into the realm of C++, you'll come to appreciate pointers and structures as indispensable assets in your programming toolkit.