in , ,

C++ Pointers to Structure

C++ Pointers to Structure
C++ Pointers to Structure

C++ Pointers to Structure

In this article, you’ll find relevant examples that will help you with working with pointers to access data inside a structure.

A pointer variable can be made not just for local sorts like (int, float, double, and so forth.) yet they can likewise be made for user characterized types like structure.

Here is the manner by which you can make pointer for structures:

#include <iostream>
using namespace std;

struct temp {
    int i;
    float f;
};

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

This program creates a pointer ptr of type structure temp.


Example: Pointers 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

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 part work using a pointer is terrible and there is elective documentation – > which is more normal.

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

Please feel free to give your comment if you face any difficulty here.

salman khan

Written by worldofitech

Leave a Reply

TutuApp

TutuApp Installer – Un-Official App Store for iOS and Android