C++ Pointers and Structures

C++ allows pointers to structures just as it allows pointers to int or char or float or any other data type. The pointers to structures are known as structure pointers.

Declaration and Use of Structure Pointers in C++

Just like other pointers, the structure pointers are declared by placing asterisk (∗) in front of a structure pointer's name.

It takes the following general form :

struct-name ∗struct-pointer;

where struct-name is the name of an already defined structure and struct-pointer is the pointer to this structure. For example, to declare dt-ptr as a pointer to already defined structure date, we shall write

date ∗ dt-ptr;

The declaration of structure type and the structure pointer can be combined in one statement. For example,

struct date {
   short int dd, mm, yy;
};
date ∗dt_ptr;

is same as

struct date {
   short int dd, mm, yy;
} ∗dt_ptr;

Using structure pointers, the members of structures are accessed using arrow operator ->. To refer to the structure members using -> operator, it is written as

struct-pointer -> structure-member

That is, to access dd and yy with dt_ptr, we shall write

dt_ptr -> yy

and

dt_ptr -> dd

C++ Structure Pointers Example

Consider the following program, which shows how to use these pointers. This C++ program demonstrates how to declare and use Structure Pointers in C++.

#include<iostream>
using namespace std;

struct date {
   short int dd, mm, yy;
   } join_date = {19, 12, 2006};

int main()
{
   date *date_ptr;
   date_ptr = &join_date;

   cout<<"Printing the structure elements using the structure variable\n";
   cout<<"dd = "<<join_date.dd<<", mm = "<<join_date.mm<<", yy = "<<join_date.yy<<"\n";
   cout<<"\nPrinting the structure elements using the structure pointer\n";
   cout<<"dd = "<<date_ptr->dd<<", mm = "<<date_ptr->mm<<", yy = "<<date_ptr->yy<<"\n";

   return 0;
}

When the preceding C++ program is compiled and executed, the following output is produced:

c++ structure pointer example

The above program is self-explanatory. Remember that the dot operator ('.') requires a structure variable on its left, and the arrow operator ('->') requires a structure pointer on its left. The arrow operator consists of the minus sign followed by a greater-than sign.

There are the following two primary uses for structure pointers:

The structure pointer is very useful in generating a call by reference call to a function because when a pointer to a structure is passed to a function, only the address of the structure is passed. This makes way for very fast function calls. A second advantage of it is when a function needs to refer to the actual structure argument instead of a copy of it; by passing a pointer, it can modify the contents of the actual elements of the structure used in the call.

Here is another example program that you can look at to get a better understanding of structure pointers in C++.

#include<iostream>

using namespace std;

struct emp
{
   int empId;
   string empName;
   float empBasic;
   float empExperience;
};

void display(emp *e);
void increase(emp *e);

int main()
{
   emp mgr, *eptr;

   cout<<"Enter the employee ID: ";
   cin>>mgr.empId;
   cout<<"Enter the name: ";
   cin>>mgr.empName;
   cout<<"Enter basic pay: ";
   cin>>mgr.empBasic;
   cout<<"Enter the experience (in years): ";
   cin>>mgr.empExperience;

   eptr = &mgr;

   cout<<"\nEmployee details before increase()\n";
   display(eptr);

   increase(eptr);
   
   cout<<"\nEmployee details after increase()\n";
   display(eptr);

   cout<<endl;
   return 0;
}

void display(emp *e)
{
   int len = (e->empName).size();

   cout<<"Employee ID: "<<e->empId;
   cout<<"\nName: "<<e->empName;
   cout<<"\tBasic: "<<e->empBasic;
   cout<<"\tExperience: "<<e->empExperience<<" years\n";
}

void increase(emp *e)
{
   if(e->empExperience >= 5)
   {
      e->empBasic = e->empBasic + 15000;
   }
}

Here are two sample runs of the aforementioned C++ program in action. One employee has less than five years of experience, while the other has more than five years. The following snapshot shows the sample run with employee details: "1006" as ID, "William" as name, "54039" as basic pay, and "4" as years of experience.

c++ pointer to structure example

That is, type "1006" and hit the ENTER key, then type "William" and hit the ENTER key again, and so on to get the above output. Now the following snapshot shows another sample run with another employee having more than 5 years of experience.

c++ structure pointers example program

Because employees with more than 5 years of experience will receive an additional salary of "15000" in addition to the basic pay, the salary was increased in the second run.

Self-Referential Structures in C++

A structure that has a member element that refers to the structure itself is known as a self-referential structure.

To understand the self-referential structures, we shall first talk about a situation. Assume you are required to write a program that stores and manipulates employee information such as empid, name, basic, experience, and so on. Going through this problem, it immediately suggests the use of structures to hold the information. However, how will these structures be stored and manipulated? For this problem, you may use a fixed-size array of structures. But a fixed-size array has some serious drawbacks. An important one of them is that the size of the array arbitrarily limits the length of the list of employees. What if you realize during program execution that the array should have been bigger? To avoid such a problem, you would certainly go for a dynamic list so that the list can be as large as free memory allows.

A dynamic linear list in C++ is called a linked list. One major use of linked lists is to create arrays of unknown size in memory.

A linked list requires that each item of information contain a link to the next element in the list. Each data item usually consists of a structure that includes information fields and a link pointer.

A linked list is a structure that has an additional pointer as an element that points to another structure of the same type.

That is, to declare the above-shown structure type, we shall write

struct Employee
{
   int empid;
   string name;
   float basic;
   float experience;
   Employee ∗next;       // pointer to the same structure type
};

The structure contains an element that refers to the structure itself. Such a structure is called a self-referential structure.

C++ Dynamic Structures

The new operator can be used to create dynamic structures, which are structures for which memory is allocated dynamically. To do so, we use the following syntax:

struct-pointer = new struct-type;

where struct-type is the predefined structure type for which the memory is being allocated, and struct-pointer is a pointer of the struct-type type that stores the address of newly allocated memory. For example, we could give to dynamically allocate memory for the employee structure defined above.

Employee ∗eptr;
eptr = new Employee;

A dynamic structure can be released using the deallocation operator delete, as shown below:

delete struct-pointer;

where struct-pointer is the same pointer that was pointing to the dynamically allocated memory. That is, to release memory, which is being pointed to by eptr, we shall write.

delete eptr;

C++ Quiz


« Previous Tutorial Next Tutorial »