Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Declare the struct before definition

Tags:

c

struct

The following is the source code that is problem:

#include <stdio.h>

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

typedef struct Bar
{
    int a;
    int b;
} Bar;

int main(void)
{
    Foo f;
    f.a = 1;
    f.b.a = 2;
    f.b.b = 3;
    printf("%d %d %d\n", f.a, f.b.a, f.b.b);

    return 0;
}

I want to declare the Bar struct in the Foo struct that keep order of the struct declarations (Foo struct is first). But I can't, it occurs some errors(One is error: unknown type name 'Bar') in the compile time.

How to do it?

like image 975
LeeGom Avatar asked Oct 03 '14 23:10

LeeGom


People also ask

Where should structs be declared?

If a struct is declared in a header file in C++, you must include the header file everywhere a struct is used and where struct member functions are defined.

Where should I define struct in C?

If the struct definition is needed from multiple . c files then it should go in the header, otherwise it doesn't have to. @M.M It is only needed in one . c file.

Can we declare struct inside main in C?

If you define the structure inside main() , the scope is limited to main() only. Any other function cannot see that definition and hence, cannot make use of that structure definition.

How do you declare a struct?

The general syntax for a struct declaration in C is: struct tag_name { type member1; type member2; /* declare as many members as desired, but the entire structure size must be known to the compiler. */ }; Here tag_name is optional in some contexts.


1 Answers

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();
}
like image 93
Johannes Avatar answered Sep 29 '22 23:09

Johannes