Unable to Initialize 2D Array

时间:2015-10-06 08:19:56

标签: c arrays gcc

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)

2 个答案:

答案 0 :(得分:5)

C and C++ arrays can be initialized only as a part of the definition statement:

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

Assignment of multiple values into an array is not supported.

答案 1 :(得分:2)

In addition to FireAphis's answer, if you are under C99 you can initialize a pointer to array of ints (not a 2D array) outside his definition using compound literals:

int (*grid_2d_array)[COLUMNS]; /* Pointer to array of n int's */

in main:

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