Lluís
Lluís

Reputation: 588

Dynamic allocation in Objective-C, returning pointers

I would like to make sure the value of the pointer myFunction() returns is available, when it's not an Obj-C object.

double * vectorComponents ();   //Just an example

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

How can I dynamically allocate these variables an then how to dealloc them. If I don't do anything it won't work. Thanks everyone.

NSLog(@":)");

Upvotes: 1

Views: 827

Answers (3)

user529758
user529758

Reputation:

You can use the C standard library functions malloc() and 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);

(Documentation)

Also:

If I don't do anything it won't work.

Perhaps it's worth mentioning that it didn't work because it invokes undefined behavior. componentSet in your code was a local auto-array - it's invalidated at the end of its scope (i. e. it's deallocated at the time the function returns - exactly what you wanted not to happen.)

Upvotes: 5

CRD
CRD

Reputation: 53010

Given your example, first question is do you really need dynamic allocation? If you just want to return the address of an array initialized inside a function you can use a static variable:

double * vectorComponents ()
{
   static double componentSet[] = {1, 2, 3};
   return componentSet;
}

If you do need a dynamic array then there are many ways to do it. If you compute the array you can malloc() the storage to be free()'ed later. If you wish to initialize a dynamic array, then maybe change the values, and return it you can use a static array to do that. For example:

double * vectorComponents2 ()
{
   static double componentSet[] = {1, 2, 3};
   double *dynamic = malloc(sizeof(componentSet));
   memcpy(dynamic, componentSet, sizeof(componentSet)); // copy values
   // modify contents of dynamic here if needed
   return dynamic;
}

Using memcpy and a static array is shorter than setting individual values and allows the contents and size of the array to be changed easily.

Upvotes: 1

Joe
Joe

Reputation: 57179

If you return a pointer that you dynamically allocate in the function then the caller will have ownership of the object and will be required to free the value.

/**
* Returns ownership, use free to release the value when done.
*/
double * vectorComponents()
{
    double *componentSet = malloc(sizeof(double) * 3);

    componentSet[0] = 1.0;
    componentSet[1] = 2.0;
    componentSet[2] = 3.0;

    return componentSet;
}

void example()
{
    double *components = vectorComponents();

    //use components

    free(components);
}

Upvotes: 2

Related Questions