Storage size of struct isn't known

Viewed 2222

I want to have my structure in the main() function scope. When I do that and use typedef I get an error: storage size of ... isn't known

typedef struct client client;

int main()
{


    struct client {
        int var;
        char c;
    };


    client person1;

    return 0;
}

I am doing this to get rid of the struct keyword.
Why do I get this error and how can I do it successfully with making the struct inside my main() function ?

3 Answers

The error you're getting is because you actually have two types named struct client declared at different scopes.

The typedef declares a struct client at file scope and gives it the alias client. When you then define struct client inside of the main function, it masks the one at file scope. When you then attempt to declare a variable of type client, it refers to struct client at file scope which was never defined.

To fix this, the typedef and the struct definition need to be in the same scope. So you can either put them both in main:

int main()
{
    typedef struct client client;
 
    struct client {
        int var;
        char c;
    };

    client person1;

    return 0;
}

Or both at file scope:

typedef struct client client;

struct client {
    int var;
    char c;
};

int main()
{
    client person1;

    return 0;
}

You can declare a struct right in typedef:

typedef struct client {
    int var;
    char c;
} client;


int main()
{
    client person1;

    return 0;
}

The typedef should be used for the things that are already defined. In your case, the client is not defined in that scope. If you want a struct inside the main the try this

// in main
typedef struct client {
        int var;
        char c;
} client;

client person1;

or you can do this in the main

struct client {
        int var;
        char c;
    };

struct client person1;
Related