Pointers to Structure in C++

Pointers to Structure in C++

Pointers to Structure in C++
A pointer variable can be created not only for native types like (intfloatdouble etc.) but they can also be created for user-defined types like structure.

Here is how you can create pointer for structures:
  1. #include <iostream>
  2. using namespace std;
  3. struct temp {
  4. int i;
  5. float f;
  6. };
  7. int main() {
  8. temp *ptr;
  9. return 0;
  10. }
This program creates a pointer ptr of type structure temp.

Example: Pointers to Structure

  1. #include <iostream>
  2. using namespace std;
  3. struct Distance
  4. {
  5. int feet;
  6. float inch;
  7. };
  8. int main()
  9. {
  10. Distance *ptr, d;
  11. ptr = &d;
  12. cout << "Enter feet: ";
  13. cin >> (*ptr).feet;
  14. cout << "Enter inch: ";
  15. cin >> (*ptr).inch;
  16. cout << "Displaying information." << endl;
  17. cout << "Distance = " << (*ptr).feet << " feet " << (*ptr).inch << " inches";
  18. return 0;
  19. }
  20. Output
    Enter feet: 4
    Enter inch: 3.5
    Displaying information.
    Distance = 4 feet 3.5 inches
    In this program, a pointer variable ptr and normal variable d of type structure Distance is defined.
    The address of variable d is stored to pointer variable, that is, ptr is pointing to variable d. Then, the member function of variable d is accessed using pointer.
    Note: Since pointer ptr is pointing to variable d in this program, (*ptr).inch and d.inch is exact same cell. Similarly, (*ptr).feet and d.feet is exact same cell.
    The syntax to access member function using pointer is ugly and there is alternative notation -> which is more common.
    ptr->feet is same as (*ptr).feet
    ptr->inch is same as (*ptr).inch

Comments

Popular posts from this blog

C++ Templates ?

C++ Program to Print Number Entered by User

Educational Website