C++ Pointer to Structure

A structure pointer in C++ is a variable that stores a structure’s memory address. When passing a structure to a function or allocating memory for the structure on the fly, a pointer to the structure is helpful.

Synatx:

struct Person {
   string name;
   int age;
   double height;
};

Person *ptr;  // declare a pointer to Person structure

To access the members of the structure through the pointer, we use the arrow operator ->:

ptr->name = "John";
ptr->age = 30;
ptr->height = 5.9;

A pointer to a structure in C++ is a strong feature that lets you pass structures to functions, create memory dynamically for structures, and use the pointer to change the data members of structures.

Example:

#include <iostream>
#include <string>
using namespace std;

struct Person {
   string name;
   int age;
   double height;
};

void display(Person *p) {
   cout << "Name: " << p->name << endl;
   cout << "Age: " << p->age << endl;
   cout << "Height: " << p->height << endl;
}

int main() {
   Person john;
   john.name = "John Doe";
   john.age = 35;
   john.height = 6.2;

   Person *ptr = &john;

   display(ptr);

   return 0;
}

Output:

Name: John Doe
Age: 35
Height: 6.2

We declare a structure called Person in this example, which has three members: name, age, and height. We also define a function called display, which displays the members of a Person structure given a pointer to it as an argument.

We build and initialize the members of a Person object called john in the main function. Then, using the address-of operator &, we declare a pointer to a Person called ptr and give it John’s memory location. The display function is then invoked, with the ptr variable sent as an input.