10

I'm developing an iOS application with latest SDK.

I want to do this on a .mm file:

@interface MyClass ()
{
   int _cars[16];

   ...
}

@end

@implementation MyClass

-(id)init
{
    self = [super init];

    if (self)
    {
        _cars = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    }

    ...
}

But I get the following error:

Array type 'int [16]' is not assignable

How can I fix this error?

VansFannel
  • 45,055
  • 107
  • 359
  • 626

2 Answers2

12

If you just want to initialize the array:

int _cars[16] = {0};

It’s safe to drop the extra zeros, the compiler will figure them out. It’s not possible to assign whole arrays in C, that’s why the compiler complains in your case. It’s only possible to initialize them, and the assignment is only considered to be initialization when when done as a part of the declaration.

zoul
  • 102,279
  • 44
  • 260
  • 354
  • If the array is an instance variable, it should be initialized to zero automatically by the `alloc` method (see [this question](http://stackoverflow.com/questions/990817/are-ints-always-initialized-to-0)). Take a look at the array contents to make sure. – zoul Mar 05 '13 at 07:15
9

Objective-C++ is no different from C, Objective-C, or C++ in this case. You have to initialize an array when you declare it:

int _cars[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

Arrays aren't assignable lvalues.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469