简体   繁体   中英

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)

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.

In addition to FireAphis's answer, if you are under C99 you can initialize a pointer to array of int s (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}
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM