Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

objective-c

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?

like image 370
Rory Harvey Avatar asked Jan 07 '12 00:01

Rory Harvey


People also ask

How do I return an array in Objective C?

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.

Can a function return a 2D array in C?

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.

How do I return in Objective C?

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 .

Can we return 2D array in C++?

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.


2 Answers

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;
}
like image 81
Carl Norum Avatar answered Oct 04 '22 00:10

Carl Norum


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.

like image 36
Jasper Blues Avatar answered Oct 04 '22 00:10

Jasper Blues