Static initialization of a structure with a pointer to another, not yet declared static variable

C is a syntactic question.

I want to make an expression like the following:

struct thingy {
    struct thingy* pointer;
}

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

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

      

I tried to declare and initialize separately, as in:

struct thingy {
    struct thingy* pointer;
}

static struct thingy thing1;
static struct thingy thing2;

thing1 = {
    .pointer = &thing2
};

thing2 = {
    .pointer = &thing1
};

      

However, I am not sure if I can declare and initialize static variables separately

Is there a way I can get them to point to each other from compilation?

+3


source to share


1 answer


You were almost there. You need to "advertise" (actually this is a preliminary definition, thanks AndreyT!) Static instances first and then initialize their definitions with your desired pointers.
static struct thingy thing1;
static struct thingy thing2;

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

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

      



Technically you only need to define forward declare beforehand thing2

.

+3


source







All Articles