C 结构的静态初始化,指针指向另一个尚未声明的静态变量

C 结构的静态初始化,指针指向另一个尚未声明的静态变量,c,syntax,C,Syntax,C语法问题 我希望做出如下声明: struct thingy { struct thingy* pointer; } static struct thingy thing1 = { .pointer = &thing2 }; static struct thingy thing2 = { .pointer = &thing1 }; 我已尝试分别声明和初始化,如: struct thingy { struct thingy* pointer;

C语法问题

我希望做出如下声明:

struct thingy {
    struct thingy* pointer;
}

static struct thingy thing1 = {
    .pointer = &thing2
};

static struct thingy thing2 = {
    .pointer = &thing1
};
我已尝试分别声明和初始化,如:

struct thingy {
    struct thingy* pointer;
}

static struct thingy thing1;
static struct thingy thing2;

thing1 = {
    .pointer = &thing2
};

thing2 = {
    .pointer = &thing1
};
但是,我不确定是否可以分别声明和初始化静态变量


有没有一种方法可以让它们在编译时相互指向?

你就快到了。您需要先“向前声明”(实际上,这是一个暂定定义,谢谢AndreyT!)静态实例,然后用所需的指针初始化它们的定义

static struct thingy thing1;
static struct thingy thing2;

static struct thingy thing1 = {
    .pointer = &thing2
};

static struct thingy thing2 = {
    .pointer = &thing1
};

从技术上讲,你只需要定义
thing2

这是一篇非常好的第一篇文章!非常感谢。我不知道在初始化过程中会重复类型签名。这是否是静态变量而不是我在中声明的变量的原因(--块中声明的变量范围是否有标准术语?--)自动范围?这是一种特殊情况,因为您希望使用
thing2
地址初始化
thing1
。一般来说,您不能引用尚未声明的标识符。@jxh:对不起,我错了。没有初始值设定项的定义是暂定定义,即使它是
静态的
。有许多定义是可以的,只要其中不超过一个是非暂定的。(我认为显式的
静态的
足以让它成为非暂时性的,但事实并非如此。)@AndreyT:不用担心。谢谢你的信息@pen:请注意,在C语言中不能真正正向声明静态变量。C没有语法。但是,C允许您多次(在同一文件中)定义同一变量,只要您确保只有一个定义具有初始值设定项。语言特性被称为暂定定义,它的存在主要是为了解决您的问题。(顺便说一句,C++不支持暂定定义)。