如何从Objective-C方法返回C样式的整数数组?这是我的代码到目前为止的样子:
功能调用:
maze = [amaze getMaze];
Run Code Online (Sandbox Code Playgroud)
功能:
-(int*) getMaze{
return maze;
}
Run Code Online (Sandbox Code Playgroud)
我今天刚开始用Objective-C写作,所以这对我来说都是新的.
在C中,如果需要从函数返回数组,则需要使用malloc为其分配内存,然后返回指向新分配内存的指针.
一旦你完成了这个记忆,你需要释放它.
就像是:
#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;
}
Run Code Online (Sandbox Code Playgroud)
这与C风格一样:)在Objective C中可能还有其他(可能更合适)的方法.但是,由于Objective C被认为是C的严格超集,所以这也有效.
如果我可以通过指针进一步扩展需要这样做.在函数中分配的C样式数组被认为是本地的,一旦函数超出范围,它们就会被自动清理.
正如另一张海报所指出的,int arr[10];从函数返回一个标准数组(例如)是一个坏主意,因为当数组返回时它不再存在.
在C中,我们通过动态分配内存malloc并使用指向返回的内存的指针来解决这个问题.
但是,除非你充分释放此内存,你可能会引入内存泄漏或其他一些讨厌的行为(例如free-ing一个malloc-ed指针两次会产生不想要的结果).
| 归档时间: |
|
| 查看次数: |
4968 次 |
| 最近记录: |