Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Init to zero a static 2D array at its declaration

I'm developing an iOS 5.0+ app with latest SDK.

I have to declare an initialize a private 2D array this way, because I'm going to use it on a C++ function:

@implementation MyClass

int myArray[NSFirstDim][NSSecondDim] = 0; <-- Error here

...

- (id)init
{
...
}

...
@end

But I can't initialize to 0 this way because I get the following message:

Array initializer must be an initializer list

How can I initialize all values to zero?

Or I can use a 2D dynamic array...

like image 493
VansFannel Avatar asked Dec 17 '25 19:12

VansFannel


1 Answers

Use

int myArray[NSFirstDim][NSSecondDim] = {0};

this is a powerful behavior from C, where you add values from start and rest (others) are initialized to 0.

In this sample code,

int arr[4][3]={1,2,3};

for (int i=0; i<4; i++) {
    for (int j=0; j<3; j++) {
        NSLog(@"%d",arr[i][j]);
    }
}

Output: 1,2,3,0,0,0,....

like image 64
Anoop Vaidya Avatar answered Dec 20 '25 11:12

Anoop Vaidya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!