gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:47:22 26 4
gpt4 key购买 nike

我需要转换一个充满 NSString 的 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;
}

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

最佳答案

您还需要为数组中的每个字符串分配内存。 strdup() 将适用于此。您还需要在数组末尾添加一个 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;
}

要释放数组,您可以使用:

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

关于objective-c - 将 NSArray 转换为 char** 并返回 c 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13064909/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com