English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C ++ Structure Pointer

In this article, you will find relevant examples that will help you use pointers to access data in the structure.

PointerVariables can not only be created for local types (int, float, double, etc.) but also for user-defined types (such asStructure) to create.

If you don't know what a pointer is, please visitC ++Pointer.

This is the method to create a structure pointer:

#include <iostream>
using namespace std;
struct temp {
    int i;
    float f;
};
int main() {
    temp *ptr;
    return 0;
}

This program creates a pointer of structure type temp named ptr.

Example: Structure Pointer

#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 inches: ";
    cin >> (*ptr->inch;
 
    cout << "Display information" << endl;
    cout << "distance = " << (*ptr->feet << " feet " << (*ptr->inch << " inches";
    return 0;
}

Output result

Enter feet: 4
Enter inches: 3.5
Display information
distance = 4 feet 3.5 inches

The program defines a structure type Distance with a pointer variable*ptr and the ordinary variable d.

The address of variable d is stored in the pointer variable, that is, ptr points to variable d, and then the member function of variable d is accessed using the pointer.

Note:Since the pointer ptr in this program points to the variable d, therefore (* ptr).inch and d.inch are completely the same units. Similarly, (* ptr).feet and d.feet are completely the same units.

The syntax for accessing member functions using pointers is ugly, but there is a more common substitute symbol->.

ptr->feet is equivalent to (*ptr).feet
ptr->inch is equivalent to (*ptr).inch