So I wanted to store some constant text and data for parts of a level in a game in a struct, then put pointers for all those structs in a struct for each level, and pointers for all the level structs into a struct for the game. This appears to work if I use variable names for each of the nested data structures. However this is rather cumbersome as, I am likely to change all of the data and rearrange all of the levels as I am developing it, so I wanted to do it without needing variable names for each level and parts of the level. I learned that you can use pointers to literals however this appears to not work when the struct you are declaring has a flexible array.
Here is an example of the kind of thing I am currently doing:
struct level_part{
const int data;
const char text[];
};
struct level_full{
const int numParts;
const struct level_part * parts[];
};
struct game{
const int numLevels;
const struct level_full * levels[];
}
const struct level_part l0p0 = { 101, "Hello" };
const struct level_part l0p1 = { 331, "Goodby" };
const struct level_part l1p0 = { 912, "No way" };
const struct level_full l0 = { 2, {&l0p0, &l0p1} };
const struct level_full l1 = { 1, {&l1p0} };
const struct game gameLevels = { 2, {&l0, &l1} };
Because the variables are only used once during the declaration and they get in the way of me wanting to rearrange and modify things, I was hoping to declare everything in one big literal. I found out you can use the pointer to a literal using something like &(int){5}
, and I wanted to do that here but I ran into an issue where the gcc compiler complained that the struct contained a flexible array “error: non-static initialization of a flexible array member” when I do something like this:
const struct level_full l1 = { 1, { &(const struct level_part){ 912, "No way" } } };
I would think that the old version of l1 is equivalent to this version, because, as far as I understand, the literal should be put in the initialized data or the text during compile time, then it should just get the pointer to that data and give it to l1. However, it appears that the compiler disagrees. Am I doing something wrong, is this just not the correct way of doing that, or is what I am trying to do just impossible in C? While I got an error in gcc I need my solution to be portable to the Windows compiler too.
If what I am doing is impossible are there any other alternatives to what I am doing? I kinda was hoping that I could just store all this constant data in the program without needing to allocate it or use a separate file.