Returning a 2D C array from an Objective-C function

前端 未结 2 495
孤独总比滥情好
孤独总比滥情好 2021-01-12 09:17

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

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

However, thi

相关标签:
2条回答
  • 2021-01-12 09:49

    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.

    0 讨论(0)
  • 2021-01-12 09:53

    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;
    }
    
    0 讨论(0)
提交回复
热议问题