C Declare the struct before definition

The compiler needs to be able to determine the size of Foo. If Bar is unknown at the time Foo is defined the compiler can not determine the size of Foo. The only way around this is using a pointer since all pointers have the same size.

You can use a forward declaration of the structure and then reference it as a pointer. This means that Foo can never automatically allocate the memory for Bar. As a consequence the memory has to be allocated separately.

If you can avoid this do not do it.

#include <stdio.h>
#include <stdlib.h>

typedef struct Bar Bar;
typedef struct Foo Foo;

struct Foo
{
    int a;
    Bar * b;
};

struct Bar
{
    int a;
    int b;
};

void dynamic(void)
{
    Foo f;

    f.a = 1;
    f.b = (Bar*)malloc(sizeof(Bar));
    f.b->a = 2;
    f.b->b = 3;
    printf("%d %d %d\n", f.a, f.b->a, f.b->b);

    free(f.b);
}

void automatic(void)
{
    Foo f;
    Bar b;

    f.a = 1;
    f.b = &b;
    f.b->a = 2;
    f.b->b = 3;
    printf("%d %d %d\n", f.a, f.b->a, f.b->b);
}

int main(void)
{
    dynamic();
    automatic();
}

Tags:

C

Struct