Jessica Cohen Jessica Cohen - 1 month ago 17
C Question

C struct within a struct hardcoded initialization

What I am doing wrong here for C99:

struct chess {
struct coordinate {
char piece;
int alive;
} pos[3];
}table[3] =
{
{
{'Q', (int)1},{'Q', (int)1},{'Q', (int)1},
{'B', (int)1},{'B', (int)1},{'B', (int)1},
{'K', (int)1},{'K', (int)1},{'K', (int)1},
}
};


I wish to be able to access the data like having a struct within a struct that:

table[row].pos[column].piece
table[row].pos[column].alive


I tried several combinations, and none seems to work for this case. I have done previous struct hard coded initialization before that works, but not a struct within a struct as this time.

Any suggestions?

Answer
struct chess {
    struct coordinate {
        char piece;
        int alive;
    } pos[3];
} table[3] =
{
    {
        .pos = {{ .piece = 'Q', .alive = 1 },
                { .piece = 'Q', .alive = 1 },
                { .piece = 'Q', .alive = 1 }
               }
    },
    {
        .pos = {{ .piece = 'B', .alive = 1 },
                { .piece = 'B', .alive = 1 },
                { .piece = 'B', .alive = 1 }
               }
    },
    {
        .pos = {{ .piece = 'K', .alive = 1 },
                { .piece = 'K', .alive = 1 },
                { .piece = 'K', .alive = 1 }
               }
    }
};

It seems to work. Just be careful about the placement of your braces, and PLEASE try to understand what you are typing. This is how to read the answer :

  1. table[3] is an array. So the initializer begin by '{' and ends by '};', with each element separated by a ','
  2. each element of this array is a 'struct chess'. So each sub-element begins by '{' and ends by '}'
  3. in each 'struct chess' you have an array 'pos[3]'. So another sub-sub '{' and '}'
  4. each 'pos' is a struct, so there is sub-sub-sub '{' and '}'
  5. finally, the fields are here. Use the C99 initializer list to make your code cleaner. And double quotes in C are char*, not char. Use single-quotes

Advices :

  • try to minimize the amount of "difficult-to-read" code. It will serve you
  • I never use nested structs. When needed, separate their codes and create function which will initialize them.
  • CPPReference is useful
  • use good variables name and identifiers for your struct. When i read 'pos', I think it is a position on a chess ((x, y) coordinates with informations).
Comments