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.
Visit pointers and structures to learn more about them.
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:
struct_pointer->name;
Let us go through an example in order to understand its use in a program.
Example of Pointer to Structure in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <iostream> using namespace std; struct Distance { int meters; float centimeters; }; int main() { Distance *ptr, len; ptr = &len; cout << "Enter meters value: "; cin >> (*ptr).meters; cout << "Enter centimeters value: "; cin >> (*ptr).centimeters; //display cout << "Distance = " << (*ptr).meters << "m " << (*ptr).centimeters << "cm"; return 0; } |
Output:
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
(*ptr).centimeters
is same as ptr->centimeters