how to initialize static array within struct

3.1k Views Asked by At

I have this struct:

typedef struct {
    int start;
    int end;
    char board[10][10]; 
} move;

when I try initializing it this way:

char new_board[10][10]
move struct new_move = {0, 0, new_board}

I get this error:

warning C4047: 'initializing' : 'char' differs in levels of indirection from 'char (*)[10]'

any suggestions?

2

There are 2 best solutions below

0
On BEST ANSWER

If you want to initialize the array by zeroes then you can write simply

move new_move = { 0 };

If you want that the structure array would contain values of array char new_board[10][10] then you have to copy its element in the structure array.

for example

char new_board[10][10] = { /* some initializers */ };

move new_move = { 0 };

memcpy( new_move.board, new_board, sizeof( new_board ) );

If board is an array of strings then you could also to copy using a loop each string in the structure array using standard C function strcpy.

0
On

First - the reason why you can't do this: if you do something like this you are saying to the compiler that you're trying to overwrite a constant pointer (a table is a constant pointer).

You can initialize the array by using two four loops like this:

int i, j
for (i = 0; i < 10; i++) 
    for (j = 0; j < 10; j++)
        new_move.board[i][j] = new_board[i][j];

That should work best in my opinion.