marcg11
marcg11

Reputation: 732

Converting NSArray to char** and returning the c array

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?

Upvotes: 2

Views: 3477

Answers (2)

trojanfoe
trojanfoe

Reputation: 122391

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);
    }
}

Upvotes: 5

Omkant
Omkant

Reputation: 9204

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);
}

Upvotes: 1

Related Questions