C++ Pointers to Structures
Pointers are a powerful concept in C++ that allow you to manipulate memory locations directly. In C++, you can use pointers with structures to access and modify structure data efficiently.
Declaring a Pointer to a Structure
To declare a pointer to a structure, use the structure name followed by an asterisk *
and the pointer name.
Example:
1struct Person 2{ 3 string name; 4 string address; 5 int age; 6}; 7 8Person *personPointer;
In this example, we have declared a pointer to a structure named personPointer
of type Person
.
Accessing Structure Members Using a Pointer
To access the members of a structure using a pointer, use the pointer name followed by the arrow ->
operator and the member name.
Example:
1#include <iostream> 2#include <string> 3using namespace std; 4 5struct Person 6{ 7 string name; 8 string address; 9 int age; 10}; 11 12int main() 13{ 14 Person person1; 15 person1.name = "William Max"; 16 person1.address = "123 Main Street"; 17 person1.age = 30; 18 19 Person *personPointer; 20 personPointer = &person1; 21 22 cout << "Name: " << personPointer->name << endl; 23 cout << "Address: " << personPointer->address << endl; 24 cout << "Age: " << personPointer->age << endl; 25 26 return 0; 27}
Output:
1Name: William Max 2Address: 123 Main Street 3Age: 30
In this example, we have defined a structure variable named person1
and assigned values to its members name
, address
, and age
. We then declared a pointer to a structure named personPointer
and assigned the address of person1
to it using the address-of operator &
. Finally, we access the members of the structure using the arrow ->
operator and print their values to the console.
Using a Pointer to Modify Structure Members
To modify the members of a structure using a pointer, use the pointer name followed by the arrow ->
operator and the member name.
Example:
1#include <iostream> 2#include <string> 3using namespace std; 4 5struct Person 6{ 7 string name; 8 string address; 9 int age; 10}; 11 12int main() 13{ 14 Person person1; 15 person1.name = "William Max"; 16 person1.address = "123 Main Street"; 17 person1.age = 30; 18 19 Person *personPointer; 20 personPointer = &person1; 21 22 cout << "Name: " << personPointer->name << endl; 23 cout << "Address: " << personPointer->address << endl; 24 cout << "Age: " << personPointer->age << endl; 25 26 personPointer->name = "Jane Max"; 27 personPointer->address = "456 Main Street"; 28 personPointer->age = 31; 29 30 cout << "Name: " << personPointer->name << endl; 31 cout << "Address: " << personPointer->address << endl; 32 cout << "Age: " << personPointer->age << endl; 33 34 return 0; 35}
Output:
1Name: William Max 2Address: 123 Main Street 3Age: 30 4Name: Jane Max 5Address: 456 Main Street 6Age: 31
In this example, we have modified the members of the structure using the pointer personPointer
and the arrow ->
operator. After modifying the values, we print the new values to the console and verify that they have been changed.