I know the internal representation of a multi-dimensional array is the same as the "flattened" array, but I'm looking here for an answer if (and if yes, how and where) the C standard allows me to do the following. Maybe I missed something, but I couldn't find any paragraph telling me that e.g. int []
and int [][]
are compatible types.
The concrete background: I did my own "toy" implementation of the Lights Out game, and I have the following in my game state structure representing the board:
struct context
{
// [...]
int board[5][5];
// [...]
};
This is a 2D array of "boolean integers" indicating whether a position is lit or not. As the game is won when all positions are unlit, I do the following to check this:
// parameter is `struct context *ctx`
for (int i = 0; i < 25; ++i)
{
if (((int *)ctx->board)[i])
{
won = 0;
break;
}
}
Now, this code works, but is it actually well-defined or should I use two nested loops iterating over both dimensions of ctx->board
?