George Sha George Sha - 11 days ago 6
C Question

error: expected specifier-qualifier-list before when creating a struct array

I'm learning C language and I have a problem.

I have a struct and I initialize it with {0}:

struct first
{
char a[5];
int b;
}first= {0};


And I'm trying to create a array of this struct in another struct with each element in the array has the value of {0}:

struct second
{
first f_array[20];
};


However, when I compile, it says error: expected specifier-qualifier-list before 'first'.

Anyone knows how to create a struct array in other struct like what I'm trying to do?

Answer

This happens because the compiler can't resolve the type of first unless you include the keyword struct in the declaration of the array like this :

struct first f_array[20];

Or use typedef :

typedef struct {
    char a[5];
    int b;
} first;

struct second {
    first f_array[20];
};

struct second obj = {{0}};

Using typedef means you no longer have to write struct all over the place and makes your code more cleaner.