使用作为结构本身的成员的

时间:2016-03-16 03:10:51

标签: c pointers struct member

我有一个包含多个成员的结构,其中一个结构本身就是相同的结构。我想要做的是有一个指向与同一结构相关的结构的指针,但它的类型相同。在读取struct成员时,编译器无法识别该类型,因为它仍然需要定义。有没有其他方法可以做我想要的事情?

typedef struct _panels
{
    int id;
    // Dimensions
    double length;
    double height;

    // Global coordinates of origin of LCS
    double origX;
    double origY;
    double origZ;

    // Orientation of local x-axis wrt global X-axis
    double angle;

    // Panel reinforcement
    int nReinforcement;
    double *xReinf; // arbitrary spacing
    double sx;  // fixed spacing
    double xReinf0; // x-coordinate of first rebar

    // CHB unit
    CHBUnit *chb;

    // Openings
    int nOpenings;
    CHBOpening *openings;

    // Pointer to adjacent panels
    CHBPanel * left;    int leftPanelID;
    CHBPanel * right;   int rightPanelID;
}CHBPanel;

1 个答案:

答案 0 :(得分:6)

您应该使用已定义的(在结构定义中不完整)类型struct _panels而不是CHBPanel(尚未定义)来声明指向结构本身的指针。

最后一部分

    CHBPanel * left;    int leftPanelID;
    CHBPanel * right;   int rightPanelID;

应该是

    struct _panels * left;    int leftPanelID;
    struct _panels * right;   int rightPanelID;

替代方式:您可以在声明结构之前执行typedef

typedef struct _panels CHBPanel;
struct _panels
{
    int id;

    /* snipped */

    // Pointer to adjacent panels
    CHBPanel * left;    int leftPanelID;
    CHBPanel * right;   int rightPanelID;
};