Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在结构中按任意顺序使用结构(C)_C_Struct_Definition - Fatal编程技术网

在结构中按任意顺序使用结构(C)

在结构中按任意顺序使用结构(C),c,struct,definition,C,Struct,Definition,我有一个非常简单的问题:我想在另一个结构中使用结构,但我想能够以任何顺序定义它们。 大概是这样的: // 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

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

// 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;

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

不同结构之间必须有一个偏序,并且您应该按照声明它们的顺序尊重它注:您的typedef缺少typedef名称,它应该是
typedef结构类型2{inti;type3t;}type2例如。使用头文件查看两者的可能重复?@TommasoDeSica对不起,我不明白您的要求。我的方法可以使用前向声明来完成。这是一个简单的方法告诉编译器“这个结构稍后会被定义,我保证。我只需要让它知道它存在”这个解决方案只针对C还是C++?我已经在C++编译器上进行了测试(现在我只有这个),我收到了一个错误。谢谢,它仍然需要转发声明才能工作。它们已经存在了,与实际声明内联。例如:
structType2*t这是向前声明
type2
并同时创建
t