1

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?

  • 2
    XY problem. The actual question is: why would one want to do this? Leave optimisations to the compiler! Too bad you don't post a [mcve] with all **relevant** code. But it is very likely you violate the effective type rule and invoke undefined behaviour. As a sidenote: using magic numbers is error prone and bad coding style. – too honest for this site Jun 17 '17 at 11:05
  • 1
    All relevant code is here. And indeed, the answers to the linked duplicate are helpful, for some reason, I didn't find this question with my searches. –  Jun 17 '17 at 11:06

0 Answers0