Unable to Initialize 2D Array

I have declared a 2D global array variable like so:

int grid_2d_array[ROWS][COLUMNS];

then in main I’ve to initialize it with hard-coded values:

grid_2d_array[ROWS][COLUMNS] = {{5, 7, 2, 8, 3, 6, 1, 4},
                                ....
                                {1, 6, 3, 2, 4, 8, 9, 5}
                                };

Example:

#include <stdio.h>

#define ROWS    9
#define COLUMNS 9

/* Global variable. */
int grid_2d_array[ROWS][COLUMNS];

int main() 
{
   /* Initialze the 2D array. */
   grid_2d_array[ROWS][COLUMNS] = {{5, 7, 2, 8, 3, 6, 1, 4},
                                   ....
                                   {1, 6, 3, 2, 4, 8, 9, 5}
                                  };

   return 0;
}

But when I try compiling the source code, GCC gives the following error:

source_file.c: In function ‘main’:
source_file.c:45:34: error: expected expression before ‘{’ token
 grid_2d_array[ROWS][COLUMNS] = {{5, 7, 2, 8, 3, 6, 1, 4},
                                ^

I’m not sure why GCC is not recognizing grid_2d_array as a global variable.

The problem goes away if I redeclare the aforementioned variable in main.

I’m running GCC version: gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04)


Source: gcc

Leave a Reply