我有一个非常简单的问题:我想在另一个结构中使用结构,但是我希望能够以我想要的任何顺序定义它们。
像这样:

// User type definition
typedef struct type1{
    int i;
    type2 t;
};
// User type definition
typedef struct type2{
    int i;
    type3 t;
};
// User type definition
typedef struct type3{
    int i;
};


我怎样才能做到这一点?

最佳答案

可以完成此操作的唯一方法是使用指向结构的指针而不是静态成员:

typedef struct type1 {
    int i;
    struct type2 *t;
} type1;
// User type definition
typedef struct type2 {
    int i;
    struct type3 *t;
} type2;
// User type definition
typedef struct type3 {
    int i;
} type3;


这样做的原因是编译器必须知道结构的大小。如果使用指针,则编译器只需知道该结构类型就存在,因为给定体系结构上的指针类型在编译时为已知大小

关于c - 以任意顺序在结构内部使用结构(C),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13728168/

10-11 20:54
查看更多