Reputation: 10442
I have
struct board{
int x[3];
int y[3];
};
// in the class PatternReader
board PatternReader::testPattern1DX() {
struct board aBoard;
int x[3] = { 1,1,1 };
aBoard = x;
return aBoard;
}
Error is "incompatible types in assignment of int *
".
How do you set arrays that are inside a struct?
Upvotes: 0
Views: 2780
Reputation: 1797
Add an initializer function to the board struct:
struct board
{
int x[3];
int y[3];
void initX(int* values)
{
for(int i = 0; i < 3; i++)
x[i] = values[i]
}
};
Then use it:
board PatternReader::testPattern1DX()
{
struct board aBoard;
int x[3] = { 1,1,1 };
aBoard.initX(x);
return aBoard;
}
Upvotes: 1
Reputation: 674
Your code
int x[3] = { 1,1,1 };
aBoard = x;
is creating a variable of type int* with the initial values 1,1,1. You are then trying to assign that to a variable of type board. You don't want to do that. I think you intended:
int x[3] = { 1,1,1 };
aBoard.x = x;
Note the .x at the end of aBoard. However, this is still wrong. You can't assign arrays like that. Look up "copying arrays" instead. Is there a function to copy an array in C/C++?
Honestly, I would suggest making board a class with constructors and and then you can make the constructors behave as you want, and also look into overloading assignment operators. But for now, trying copying from x to aBoard.x is probably what you want.
Upvotes: 0
Reputation: 613592
You cannot assign arrays. However, you can can initialize the struct:
board PatternReader::testPattern1DX()
{
board aBoard = {
{1, 1, 1},
{2, 2, 2}
};
return aBoard;
}
This initializes y
as well as x
.
Upvotes: 4