Reputation: 826
I am fairly new to C and have a bit of a trouble using an array as a part of a struct. I have a struct defined as follows:
typedef struct
{
int row;
int col;
int * puzzle[5][5]
} data;
Later on in a function, I am trying to use this struct as follows:
void foo(int grid[5][5])
{
data *puz = (data *)malloc(sizeof(data));
puz->row = 3;
puz->col = 2;
puz->puzzle = grid; // causes an error
}
The last statement produces an error "assignment to expression with array type". I understand that this has something to do with the equal sign and array data structure, but I am not sure how to resolve this. Any help is greatly appreciated. Thank you.
Upvotes: 0
Views: 75
Reputation: 180201
This ...
int * puzzle[5][5]
... declares puzzle
as an array of 5 arrays of 5 pointers to int
each. Colloquially, we more often call such a thing a 5 x 5 array, but the key thing you should appreciate is that the underlying scalar element type is a pointer type. That does not match the scalar element type (int
) of the parameter of function foo
, and it is anyway unlikely to be what you want. (Note also that your code omits the required semicolon after that member's declaration.)
It seems likely that the structure member should instead be declared as ...
int puzzle[5][5];
... i.e. a 2D array of int
. C does not have whole-array assignment, so in that case you need a different way to copy the function parameter into the new structure. You could write a set of nested loops, but it is more straightforward to use memcpy()
:
memcpy(&puz->puzzle, grid, sizeof(puz->puzzle));
In the unlikely event that you want your structure to contain a pointer to an array, then you might declare it either as
int (*puzzle)[5];
or
int (*puzzle)[5][5];
or even
int *puzzle;
Which of those you chose would affect how you assign to the member and how you access the int
array elements. Since I don't think any of these are what you're actually after, I leave the details as an exercise.
Upvotes: 2
Reputation: 362
I think you should call the function with a pointer to the array, and modify the function signature accordingly. But if you want to copy the array rather than point to it, you should perform something like memcpy.
Upvotes: 0