Reputation: 391
My initialization of my array is getting a weird error. Anything I'm missing? The error is at the gameBoard
array.
@implementation TicTacToe
- (id)init
{
self = [super init];
if (self)
{
gameBoard [3][3] = {{0, 0, 0},
{0, 0, 0},
{0, 0, 0}}; // error is saying: "expected expression"
turn = 1;
winner = 0;
cellsChosen = 0;
}
...
Upvotes: 0
Views: 475
Reputation: 6205
You have your gameBoard
declared in @interface TicTacToe
, right? Then you cannot use C array initialization syntax, because your array is already initialized. Unfortunately C doesn't provide a shortcut to assign arrays, so you should create a temporary array initialized with your values and then use memcpy
to copy its elements to your array.
...
if (self)
{
int tmpGameBoard[3][3] = {{0, 0, 0},
{0, 0, 0},
{0, 0, 0}};
NSAssert(sizeof(tmpGameBoard) == sizeof(gameBoard),
@"gameBoard is not a 3x3 array");
memcpy(gameBoard, tmpGameBoard, sizeof(tmpGameBoard));
...
NSAssert
is used to make sure you haven't changed your array size in interface and forgot to update its initialization (It would be better to use compile time assertion instead of NSAssert
, but that's another topic).
Upvotes: 1
Reputation: 104698
an objc initializer is not a 'proper' initializer. your memory for your ivars already exists and it has been initialized with zeroed memory. so you are not using actual initialization syntax in this scope. this is why a const
ivar is not useful, unless you are happy with using zeroed memory exclusively for that ivar (or you're into breaking const
promises).
you can use assignment for the type (creating a temporary), or you can use the usual memory copying.
Upvotes: 0