0

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?

David G
  • 94,763
  • 41
  • 167
  • 253
bogen
  • 9,954
  • 9
  • 50
  • 89

3 Answers3

4

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • 1
    @TheOn It is valid code for C++ 2003 because board is an aggregate. – Vlad from Moscow Feb 05 '14 at 19:35
  • hmm..I should do research next time lol, thanks for correcting me, comment removed – Creris Feb 05 '14 at 19:37
  • Directly initializing the variable, rather than initializing a separate variable and then performing an assignment, is the right thing to do. However it is also a good idea to avoid raw arrays and to use `std::array` instead. This answer still works after replacing the raw arrays with `std::array`. – bames53 Feb 05 '14 at 19:58
1

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;
}
Lother
  • 1,699
  • 1
  • 12
  • 17
0

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.

Community
  • 1
  • 1
m24p
  • 664
  • 4
  • 12
  • 2
    "is creating a variable of type int*" No, arrays and pointers are not the same. The variable is in fact an array and its type is 'array of 3 ints'. If it were really a pointer then this would be legal: `int x[3] = {1,1,1}; x = nullptr;` – bames53 Feb 05 '14 at 19:50
  • Thank you for making sure the technical stuff is accurate. Yes, arrays and pointers are not exactly the same. I used the term "int*" because in the code `aBoard = x;` it tries to assign aBoard to the int* from x, thus the error: "incompatible types in assignment of int *" – m24p Feb 05 '14 at 20:04