Use of memset to prevent ''variable-sized object may not be initialized'

67 views Asked by At

I am trying to set values to a 2D array (envisage a game board or a some grid) using the code below but I receive 'variable-sized object may not be initialized' error.

I tried solving it using memset but to no avail.

Many thanks and some hints would be much appreciated.


// constants
#define DIM_MIN 3
#define DIM_MAX 9

// board
int board[DIM_MAX][DIM_MAX];


void init(void)
{
  int highest = d^2;

  for (int i = 0; i < d; i++)
    {
        for (int j = 0; j < d; j++)
        {
            int board[i][j] = highest - 1;
        }
    }
    if (d % 2 == 0)
    {
        int board[d-1][d-2] = 2;
        int board[d-1][d-3] = 1;
    }    
}
1

There are 1 answers

1
Sourav Ghosh On BEST ANSWER

The problem is with the code in for loop body, which says

  int board[i][j] = highest - 1;

what you want probably is

  board[i][j] = highest - 1;

The same goes for the if condition body, too.

To elaborate regarding the error message, int board[i][j] = highest - 1; tries to define a new VLA (variable length array), which cannot be initialized.

Quoting C11, chapter ยง6.7.9, Initialization (emphasis mine)

The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.