C++中指向结构体的指针也可以称为结构体指针。C++中的结构体指针 被定义为指向存储结构体的内存块地址的指针。下面是一个相同的例子:
句法:
结构体名称*ptr;
// 结构体的初始化如下所示
ptr = &struction_variable;
示例1:
// 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;
}
在上面的代码中,g是struct point的一个实例,ptr是struct指针,因为它存储的是struct point的地址。
示例2:
// 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;
}
输出
16