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?
Objective-C programming language does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.
This can be done by creating a two-dimensional array inside a function, allocating a memory and returning that array. The important thing is you need to FREE the matrix that was allocated. The source code of returning a two-dimensional array with reference to matrix addition is given here. #include <stdio.
The value given in the return statement is the value returned by the function or method. In your example, the value in accumulator will be the result of calling the method -add: , like this: double bar = [foo add:3.1]; bar will get the value that was in accumulator .
Use Pointer to Pointer Notation to Return 2D Array From Function in C++ As an alternative, we can use a pointer to pointer notation to return the array from the function. This method has an advantage over others if the objects to be returned are allocated dynamically.
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With