7

I want to do achieve something like this in Objective-C

+(int[10][10])returnArray
{
    int array[10][10];
    return array;
}

However, this gives an "array initializer must be an initializer list" compiler error. Is this at all possible?

2 Answers 2

9

You can't return an array (of any dimension) in C or in Objective-C. Since arrays aren't lvalues, you wouldn't be able to assign the return value to a variable, so there's no meaningful for such a thing to happen. You can work around it, however. You'll need to return a pointer, or pull a trick like putting your array in a structure:

// return a pointer
+(int (*)[10][10])returnArray
{
    int (*array)[10][10] = malloc(10 * 10 * sizeof(int));
    return array;
}

// return a structure
struct array {
  int array[10][10];
};

+(struct array)returnArray
{
   struct array array;
   return array;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Looking at that code, it appears I use array in lot of different namespaces. I'll clean it up if you think it's confusing.
When using the struct method, how do I access the struct as a 2d array? For instance when I do int i = array[0][1] I get "subscripted value is not an array, pointer, or vector"
You need to access the structure member. int i = array.array[0][1] should do it for you.
1

Another way you can do it with objective C++, is to declare the array as follows:

@interface Hills : NSObject
{


@public
    CGPoint hillVertices[kMaxHillVertices];
}

This means the array is owned by the Hills class instance - ie it will go away when that class does. You can then access from another class as follows:

_hills->hillVertices 

I prefer the techniques Carl Norum describes, but wanted to present this as an option that might be useful in some cases - for example to pass data into OpenGL from a builder class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.