Objective-C中的动态分配,返回指针

Llu*_*uís 1 cocoa allocation dynamic objective-c

我想确保指针myFunction()返回的值是可用的,当它不是Obj-C对象时.

double * vectorComponents ();   //Just an example

double * vectorComponents ()
{
    double componentSet[] = {1, 2, 3};
    return componentSet;
}
Run Code Online (Sandbox Code Playgroud)

如何动态分配这些变量然后如何解除它们.如果我什么都不做就行不通.感谢大家.

NSLog(@":)");
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以使用C标准库函数malloc()free():

double *vectorComponents()
{
    double *componentSet = malloc(sizeof(*componentSet) * 3);
    componentSet[0] = 1;
    componentSet[1] = 2;
    componentSet[2] = 3;
    return componentSet;
}

double *comps = vectorComponents();

// do something with them, then
free(comps);
Run Code Online (Sandbox Code Playgroud)

(文件)

也:

如果我什么都不做就行不通.

也许值得一提的是它没有用,因为它调用了未定义的行为.componentSet在你的代码中是一个本地自动数组 - 它在其作用域的末尾无效(即它在函数返回时被释放 - 正是你想要不发生的.)