Pointers to Structure in C++

Pointers to Structure in C++

A pointer variable can be created not only for int, float, double etc. but also be created for user defined types like structure.

Pointers are variables whichis used store address of another variables. A structure is auser defined data type which is the collection of variables of different types under a single name .A structure pointer is a type of pointer and it stores the address of a structure type variable.

Create pointer for structures

#include <iostream>
using namespace std;

struct temp {
    int i;
    float f;
};

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

Program of 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 << "Information." << endl;
    cout << "Distance = " << (*ptr).feet << " feet " << (*ptr).inch << " inches";

    return 0;
}

Output

Enter feet: 5
Enter inch: 5.5
Information.
Distance = 5 feet 5.5 inches

 

Read more, Structure and function in C++

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *