Pointer to Structure In C++

Pointer to Structure In C++ with Example

Structure Pointer: The term “structure pointer” refers to a pointer that points to the location of a memory block containing a structure. Here is an illustration of the same:

You’ll discover useful examples in this article that will assist you in using pointers to access data within a structure.

We will talk about the C programming language’s Structure pointer in this part. Let’s comprehend the Structure before moving on to the concepts.

The structure is a grouping of various data types that have been given the same name via the struct keyword.

The programmer can store records of various data types in the Structure using this type of data type, also referred to as the user-defined data type. Additionally, the term “member” refers to the grouping of data pieces inside the Structure.

In addition to creating pointer variables for user-defined types like structure, pointer variables can also be formed for native types like (int, float, double, etc.).

Visit C++ pointers if you are unfamiliar with pointers.

The following describes how to construct pointers for structures:

#include <iostream>
using namespace std;

struct temp {
    int i;
    float f;
};

int main() {
    temp *ptr;
    return 0;
}

This application generates a temporary structure pointer ptr.

Example: Pointer to Structure

#include <iostream>
using namespace std;

struct Distance {
    int feet;
    float inch;
};

int main() {
    Distance *ptr, d;

    ptr = &d;
    
    cout << "Enter feet: ";
    cin >> (*ptr).feet;
    cout << "Enter inch: ";
    cin >> (*ptr).inch;
 
    cout << "Displaying information." << endl;
    cout << "Distance = " << (*ptr).feet << " feet " << (*ptr).inch << " inches";

    return 0;
}

Output

Enter feet: 4
Enter inch: 3.5
Displaying information.
Distance = 4 feet 3.5 inches

A pointers variable named ptr and a regular variable named d, both of type structure Distance, are defined in this application.

The address of variable d is saved in the pointer variable, which means that variable d is pointed to by ptr. Then, a pointer is used to access the member function of the variable d.

Note:In this programme, the pointer ptr points to the variable d, therefore (ptr).inch and d.inch are equal. The same is true for (ptr).feet and d.feet. However, since the. operator has a greater precedence than the * operator when we are using pointers, it is much better to access struct members via the -> operator. Therefore, while using (*ptr).inch, we enclose *ptr in brackets. As a result, combining both operators in a single code makes mistakes more likely.

ptr->feet is same as (ptr).

feet ptr->inch is same as (ptr).inc

You may like:

Structure and Function In C++

Leave a Reply