Return 2D C array from Objective-C function

I want to do something like this in Objective-C

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

However, this gives an array initializer compiler error. Is it possible?

+6
source share
2 answers

You cannot return an array (of any dimension) in C or in Objective-C. Since arrays are not lvalues, you cannot assign the return value to a variable, so there is no point in such a situation. However, you can get around this. You will need to return a pointer or pull out a trick, for example, put 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; } 
+8
source

Another way you can do this with object C ++ is to declare an array as follows:

 @interface Hills : NSObject { @public CGPoint hillVertices[kMaxHillVertices]; } 

This means that the array belongs to an instance of the Hills class, i.e. he will disappear when this class does. Then you can access from another class as follows:

 _hills->hillVertices 

I prefer the methods described by Carl Norum, but I wanted to present this as an option that can be useful in some cases, for example, for transferring data to OpenGL from the builder class.

+1
source

Source: https://habr.com/ru/post/905374/


All Articles