c - Assign to 2D array a 2D array in a struct -
i have function tries loop through 2d array in struct:
typedef struct node { int grid[3][3]; } node; void somefunction(node *node) { int grid[3][3] = node->grid; //loop through }
when try compile
mp.c:42: error: invalid initializer
you cannot assign arrays in c. not allowed. when wrote:
int grid[3][3] = node->grid;
you attempting initialize local array, grid
, passed in node
. if permitted (which isn't), you'd not need loop afterwards.
you can assign structures, though, if contain arrays, if local structure node
, have written:
node local = *node;
you not need loop through arrays afterwards initialize local
.
you can loop through arrays, doing copy 1 element @ time:
for (int = 0; < 3; i++) (int j = 0; j < 3; j++) grid[i][j] = node->grid[i][j];
you can use memmove()
or memcpy()
:
int grid[3][3]; assert(sizeof(grid) == sizeof(node->grid)); memcpy(grid, node->grid, sizeof(grid));
at 1 time, answer suggested:
change line:
int grid[3][3] = node->grid;
to:
int **grid = node->grid;
i noted not work - , legitimately challenged explain why. requires space , formatting.
first of all, compiler notes:
warning: initialization incompatible pointer type
that saying 'you playing fire'.
let's suppose ignore warning. local grid
points @ top-left corner of array (if see arrays growing down , across left-to-right). value stored there plain number, not initialized pointer, when compiler evaluates grid[0]
, forced assume produce pointer. if node->grid[0][0]
contains zero, segmentation fault , core dump dereferencing null pointer (on assumption pointers , int
same size, true on 32-bit systems), or other undefined behaviour. if node->grid[0][0]
contains value, behaviour still undefined, not quite predictable.
Comments
Post a Comment