Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a C-style array of integers in Objective-C?

Tags:

c

objective-c

How to return a C-style array of integers from an Objective-C method? This is what my code looks like so far:

Function call:

maze = [amaze getMaze];

Function:

-(int*) getMaze{
    return maze;
}

I just started writing in Objective-C today so this is all new to me.

like image 703
mlclmss Avatar asked Jan 13 '23 04:01

mlclmss


1 Answers

In C if you need to return an array from a function, you need to allocate memory for it using malloc and then return the pointer pointing to the newly allocated memory.

Once you're done working with this memory you need to free it.

Something like:

#include <stdlib.h> /* need this include at top for malloc and free */

int* foo(int size)
{
    int* out = malloc(sizeof(int) * size); /* need to get the size of the int type and multiply it 
                                            * by the number of integers we would like to return */

    return out; /* returning pointer to the function calling foo(). 
                 * Don't forget to free the memory allocated with malloc */
}

int main()
{
    ... /* some code here */

    int* int_ptr = foo(25); /* int_ptr now points to the memory allocated in foo */

    ... /* some more code */

    free(int_ptr); /* we're done with this, let's free it */

    ...

    return 0;
}

This is as C style as it gets :) There are probably other (arguably more suitable) ways to do this in Objective C. However, as Objective C is considered a strict superset of C, this would also work.

If I may further expand on the need to do this by pointers. C-style arrays allocated in a function are considered local, once the function is out of scope they are automatically cleaned up.

As pointed out by another poster, returning a standard array (e.g. int arr[10];) from a function is a bad idea as by the time the array is returned it no longer exists.

In C we get around this problem by allocating memory dynamically using malloc and having a pointer that points to that memory returned.

However unless you free this memory adequately, you may introduce a memory leak or some other nasty behavior (e.g. free-ing a malloc-ed pointer twice will produce unwanted results).

like image 98
Nobilis Avatar answered Jan 17 '23 13:01

Nobilis