MaxGabriel
MaxGabriel

Reputation: 7707

Returning a 2D C array of type id in Objective-C

I'm using a 2D C array of ids in my iOS app. Is it possible to return this in an objective-C method? As an alternative solution, I tried to return a pointer to a 2D C array of integers, but I cannot modify the 2D-int array.

- (int (*)[8][8])board:(Piece *)piece
{

    int (*layout)[8][8] = malloc(8 * 8 * sizeof(int));

    //Cannot modify layout 2D C array

    return layout;
}

I have some experience in Objective-C, but none in C. Am I likely to continually run into problems using C 2D arrays, such that I should make a 2D-Array Objective-C class? What is the more typical approach an iOS developer would use?

Upvotes: 0

Views: 855

Answers (2)

asaelr
asaelr

Reputation: 5456

After you declare int (*layout)[8][8] = malloc(8 * 8 * sizeof(int));, You can change the values like (*layout)[x][y]=val;. But I recommend you to declare int (*layout)[8], so you can access elements by simply layout[x][y]=val.

Edit: I don't know about Objective-C, but in C, the function I suggested will look like:

int (*newarray())[8] {
 int (*l)[8]=malloc(64*sizeof(int));
 // You can do stuff like l[2][4]=15 here
 return l;
}

Upvotes: 0

JustSid
JustSid

Reputation: 25318

- (int **)board:(Piece *)piece
{

    int **layout = malloc(8 * sizeof(int *));
    for(int i=0; i<8; i++)
       layout[i] = malloc(8 * sizeof(int));


    return layout;
}

Don't forget to free the memory in the end. Also, you could also use a one dimensional array and something like this to access it in a similar way:

#define access(array, x, y) array[y * 8 + x]

There is also now drop in multi-dimensional array class in Objective-C, but you could create a NSArray with other NSArray's inside of it, or, google if someone else did this (I remember at least one implementation but can't recall its name)

Upvotes: 1

Related Questions