You cannot assign arrays in C. It is simply not allowed. When you wrote:
int grid[3][3] = node->grid;
you were attempting to initialize the local array, grid
, from the passed in node
. If that were permitted (which it isn't), then you'd not need a loop afterwards.
You can assign structures, though, even if they contain arrays, so if the local structure were a Node
, you could have written:
Node local = *node;
You would not need to loop through the arrays afterwards to initialize local
.
You can loop through the arrays, doing the copy one element at a time:
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
grid[i][j] = node->grid[i][j];
You can also use memmove()
or memcpy()
:
int grid[3][3];
assert(sizeof(grid) == sizeof(node->grid));
memcpy(grid, node->grid, sizeof(grid));
At one time, another answer suggested:
Change the line:
int grid[3][3] = node->grid;
to:
int **grid = node->grid;
I noted that this will not work - and was legitimately challenged to explain why. That requires space and formatting.
First of all, the compiler notes:
warning: initialization from incompatible pointer type
That is saying 'you are playing with fire'.
Let's suppose we ignore that warning. The local grid
now points at the top-left corner of the array (if you see arrays growing down and across from left-to-right). The value stored there is a plain number, not an initialized pointer, but when the compiler evaluates grid[0]
, it is forced to assume that will produce a pointer. If node->grid[0][0]
contains a zero, you will probably get a segmentation fault and core dump for dereferencing a null pointer (on the assumption that pointers and int
are the same size, which is generally true on 32-bit systems), or some other undefined behaviour. If node->grid[0][0]
contains another value, then the behaviour is still undefined, but not quite as predictable.