将 NSArray 转换为 char** 并返回 c 数组

mar*_*g11 2 c arrays objective-c

我需要转换一个用 NSStrings 填充的 NSarray 并将这个 c 数组返回给函数。

-(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;     
}
Run Code Online (Sandbox Code Playgroud)

我有这个代码,但是如果我要返回东西,我应该什么时候释放内存?

tro*_*foe 5

您还需要为数组中的每个字符串分配内存。 strdup()会为此工作。您还需要将 a 添加NULL到数组的末尾,以便您知道它在哪里结束:

- (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;     
}
Run Code Online (Sandbox Code Playgroud)

要释放阵列,您可以使用:

- (void)freeArray:(char **)array
{
    if (array != NULL)
    {
        for (unsigned index = 0; array[index] != NULL; index++)
        {
            free(array[index]);
        }
        free(array);
    }
}
Run Code Online (Sandbox Code Playgroud)