2

I need to convert an NSarray filled with NSStrings and return this c array to the function.

-(char**) getArray{
        int count = [a_array count];
        char** array = calloc(count, sizeof(char*));

        for(int i = 0; i < count; i++)
        {
             array[i] = [[a_array objectAtIndex:i] UTF8String];
        }
        return array;     
}

I have this code, but when should i free the memory if I'm returning stuff?

3
  • which memory do you want to free? array ? Commented Oct 25, 2012 at 8:52
  • in getArray definition you are missing parenthesis (), am i right ? Commented Oct 25, 2012 at 8:59
  • Lot many things are not clear here .. what is a_array ? and if you are putting characters in array[i] then you have to allocate memory for each array[i] also Commented Oct 25, 2012 at 9:03

2 Answers 2

5

You need to allocate memory for each string in the array as well. strdup() would work for this. You also need to add a NULL to the end of the array, so you know where it ends:

- (char**)getArray
{
    unsigned count = [a_array count];
    char **array = (char **)malloc((count + 1) * sizeof(char*));

    for (unsigned i = 0; i < count; i++)
    {
         array[i] = strdup([[a_array objectAtIndex:i] UTF8String]);
    }
    array[count] = NULL;
    return array;     
}

To free the array, you can use:

- (void)freeArray:(char **)array
{
    if (array != NULL)
    {
        for (unsigned index = 0; array[index] != NULL; index++)
        {
            free(array[index]);
        }
        free(array);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

getArray function should be changed to -(char**)getArray:(NSArray*)a_array{} to pass in the array name
1

array you return will be caught in some char** identifier in calling environment of getArray() function using that you can free the memory which you have allocated using calloc() inside getArray() function

int main()
{
 char **a=getArray();
 //use  a as your requirement
 free(a);
}

2 Comments

Oh so the freeing is outside of the function. So much time in objective-c that i forget everything in C...TT
Yeah you can free outside because the outside identifier itself pointing to the same memory on heap which you have allocated using calloc....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.