c++

C++ Pointers to Structure

In this tutorial we are going to learn about how to use pointers to access data from structure.

A pointer can have data type other than predefined data types (i.e int, float, char or double etc.). Pointers can have user defined data types also like Structure.

Let us take an example:

#include <iostream>

using namespace std;

struct Student {

 int roll;
 char grade;
 float per;
};

int main() {

 Student S;
 Student *p;
 p=&S;
 return 0;
}

This program creates a pointer p of type structure student which is pointing to the memory address of variable s of type structure student.


Example 1 : Pointer to Structure

#include <iostream>

using namespace std;

struct Student
{

     int roll;
     char grade;
     float per;
};

int main()
{

     Student S;
     Student *p;

     p = &S;

     cout << "Enter roll: ";
     cin >> (*p).roll;
     cout << "Enter grade: ";
     cin >> (*p).grade;
     cout << "Enter percentage: ";
     cin >> (*p).per;
     cout << "Displaying information." << endl;
     cout << "roll = " << (*p).roll << " grade " << (*p).grade <<
    "percentage"<<(*p).per;

     return 0;

}

There are two ways for accessing the members of the structure through pointer:

  1. (*p).data_member;
  2. p->data_member;

The second way (i.e. p->data_member) is the most easy and widely used way with structure as well as class. So the above example can also be written as:

#include <iostream>
using namespace std;

struct Student
{
     int roll;
     char grade;
     float per;
};

int main()
{
     Student S;
     Student *p;

     p = &S;

     cout << "Enter roll: ";
     cin >> p->roll;
     cout << "Enter grade: ";
     cin >> p->grade;
     cout << "Enter percentage: ";
     cin >> p->per;

     cout << "Displaying information." << endl;
     cout << "roll = " << p->roll << endl << "grade " << p->grade << endl
    <<"percentage"<< p->per;

     return 0;
}

Output :

Enter roll: 10
Enter grade: A
Enter percentage: 90
Displaying information.
roll: 10
grade: A
percentage: 90

In this program, a pointer variable p and normal variable s of type structure Student is defined.

The address of variable s is stored to pointer variable, that is, p is pointing to the memory address of variable s. Then, the member function of variable s is accessed using pointer.

Note: Since pointer p is pointing to the memory address of variable s in this program, p->roll and s.roll is exact same cell.

Similarly,
p->grade and s.grade is exact same cell.
p->per and s.per is exact same cell.