简体   繁体   中英

how to set a int array inside a struct in c++

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?

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 .

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM