Pointer to structure in C++ can also be referred to as Structure Pointer. A structure Pointer in C++ is defined as the pointer which points to the address of the memory block that stores a structure. Below is an example of the same:
Syntax:
struct name_of_structure *ptr; // Initialization of structure is done as shown below ptr = &structure_variable;
Example 1:
C++
// C++ program to demonstrate Pointer to Structure #include <iostream> using namespace std;
struct point {
int value;
}; int main()
{ struct point g;
// Initialization of the structure pointer
struct point* ptr = &g;
return 0;
} |
In the above code g is an instance of struct point and ptr is the struct pointer because it is storing the address of struct point.
Example 2:
C++
// C++ program to Demonstrate Pointer to Structure #include <iostream> #include <stdio.h> using namespace std;
// Structure declaration for // vertices struct GFG {
int x;
int y;
}; // Structure declaration for // Square struct square {
// An object left is declared
// with 'GFG'
struct GFG left;
// An object right is declared
// with 'GFG'
struct GFG right;
}; // Function to calculate area of // the given Square void area_Square( struct square s)
{ // Find the area of the Square
// using variables of point
// structure where variables of
// point structure is accessed
// by left and right objects
int area = (s.right.x) * (s.left.x);
// Print the area
cout << area << endl;
} // Driver Code int main()
{ // Initialize variable 's'
// with vertices of Square
struct square s = { { 4, 4 }, { 4, 4 } };
// Function Call
area_Square(s);
return 0;
} |
Output
16
Article Tags :
Recommended Articles