Redeclare 2d array of BOOL type in iOS app

2019-08-12 14:20发布

I am developing iOS application, I have created 2d array of BOOL in my public interface in .h file like this

BOOL array[10][10];

Now in .m file in some function i want to redecalre it with some other size may be

array[20][20]

How can i do that?

2条回答
一纸荒年 Trace。
2楼-- · 2019-08-12 14:28

if you use C array they are immutable, once you alloc an array of a fixed size you cannot change it.

I have posted a solution here on a possibile implementation for 2d arrays using subscription:

Objective-c syntax for 2d array instance variable

if you use C array you have to manage the memory yourself, so you can declare a pointer to a 2d array in the .h and alloc memory using new, free, realloc and copy if a bigger array is necessary. i dont suggest this approach.

查看更多
smile是对你的礼貌
3楼-- · 2019-08-12 14:30

The simple answer is that you cannot. For C-Arrays the only thing you can do short of creating a structure and its associated functions is the following:

// In your .h file you declare your arry this way:
extern BOOL *array;

// Assuming that you store _sizeI and _sizeJ for later indexing
// This gives you a 10x10 array of bools
_sizeI = 10;
_sizeJ = 10;
array  = calloc(_sizeI * _sizeJ, sizeof(BOOL));

// You index it as follows for array[i][j]
// You might use a macro for indexing.
BOOL value = array[_sizeI * i + j];

// To resize the array to a 20x20 array
free(array);
_sizeI = 20;
_sizeJ = 20;
array = calloc(_sizeI * _sizeJ, sizeof(BOOL));

I would suggest either using nested NSArrays or creating a structure and associated functions for manipulating that dynamically resized array.

查看更多
登录 后发表回答