开发者

objective-c variable length array global scope

is it possible to declare a variable length array with global scope in objective-c?

I'm making a game with a world class, which initializes the world map as a three dimensional integer array. while it's only a two dimensional side scroller, the third dimension of the list states which kinda of block goes at the coordinate given by the first two dimensions

after the initialization function, a method nextFrame: is scheduled (I'm u开发者_JS百科sing cocos2d and the CCDirector schedule method). I was wondering how to pass the int[][][] map array from the initialization function to the nextFrame function

I tried using global (static keyword) declaration, but got an error saying that global arrays cannot be variable length

the actual line of code I'm referring to is:

int map[xmax][ymax][3];

where xmax and ymax are the farthest x and y coordinates in the list of coordinates that defines the stage.

I'd like to somehow pass them to nextFrame:, which is scheduled in

[self schedule:@selector(nextFrame:)];

I realize I can use NSMutableArray, but NSMutableArray is kinda a headache for 3-dimensional lists of integers (I have to use wrapper numbers for everything...). is there any way to do this with integer arrays?


You can't have a statically allocated global array of dynamic dimensions in C (of which Objective C is a clean superset). But you can use a global array of any length or size (up to available memory) at runtime by using a global pointer, malloc, and array indexing arithmetic.

static int *map = NULL;

...
map = malloc (dim1 * dim2 * dim3 * sizeof(int));  // in some initialization method

if (map == NULL) { /* handle error */ }    // before first array access

...
myElement = map[ index3 + dim2 * ( index2 + dim1 * index1 ) ];  // some macro might be suitable here

Or you could make Objective C getter and setter methods that checks the array and array bounds on every access, since a method can return plain C data types.

Another option, if you know the max dimensions you want to have available and are willing to use (waste) that amount of memory, is to just statically allocate the max array, and throw an exception if the program tries to set up something larger than your allowed max.


I tried using global (static keyword) declaration, but got an error saying that global arrays cannot be variable length

But global array pointers can point to arrays of variable length.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜