I have a function which tries to loop through a 2D array in a struct:
typedef struct node
{
int grid[3][3];
} Node;
void someFunction(Node *node) {
int grid[3][3] = node->grid;
//loop through
}
When I try to compile this however I get a
mp.c:42: error: invalid initializer
You cannot assign arrays in C. It is simply not allowed. When you wrote:
you were attempting to initialize the local array,
grid, from the passed innode. 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: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:
You can also use
memmove()ormemcpy():At one time, another answer suggested:
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:
That is saying ‘you are playing with fire’.
Let’s suppose we ignore that warning. The local
gridnow 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 evaluatesgrid[0], it is forced to assume that will produce a pointer. Ifnode->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 andintare the same size, which is generally true on 32-bit systems), or some other undefined behaviour. Ifnode->grid[0][0]contains another value, then the behaviour is still undefined, but not quite as predictable.