A pointer in C++ can also be created for a user-defined type like structure. It is similar to those pointers that point to the native data types such as int, float, etc.
Creating pointer for structures:
We create a pointer for structure in the same way we create a pointer for any other variable.
struct Student *struct_pointer;
Now we can store the address of the structure variable in the following way.
struct_pointer = &s1;
To access the members of a structure using a pointer can be achieved by
-> operator such as:
Let us go through an example in order to understand its use in a program.
Example of Pointer to Structure in C++
using namespace std;
Distance *ptr, len;
ptr = &len;
cout << "Enter meters value: ";
cin >> (*ptr).meters;
cout << "Enter centimeters value: ";
cin >> (*ptr).centimeters;
cout << "Distance = " << (*ptr).meters << "m " << (*ptr).centimeters << "cm";
Enter meters value: 8
Enter centimeters value: 25
Distance = 8m 25cm
Also, as you can see in the above program we use
. (dot operator) to access members from the pointer. However,
-> operator is preferred over
. (dot operator) while using pointers. Because
. (dot operator) has higher precedence than the
* operator that is why we enclose the pointer within brackets
(*ptr).meters. Therefore we can conclude the following:
(*ptr).meters is same as ptr->meters
centimeters is same as ptr->