Is it possible to divide a function into two parts using struct?

65 views Asked by At

As the title says, I tried this following example :

struct tparams {
    double y;
    double* dxda;
};

typedef struct tparams Struct;

Struct cof( ) {
    Struct s;
    double y;
    double* dxda= (double*)malloc(12 * sizeof(*dxda));
    
    double a = 50;
    double b = 78;

    y= pow((a * b) / 4, 2);
    
    *dxda = (a / 8) * pow(b, 2);

    s.dxda = dxda;
    s.y = y;
    return s;
}   

void func() {
    Struct result;
    double y;

    result = cof();
    y = result.y;
    printf("result1: %g \n", y);
}

void deriv() {
    Struct result;
    double* dxda = (double*)malloc(12 * sizeof(*dxda));

    result = cof();
    dxda = result.dxda;
    printf("result2: %g \n", *dxda);        
}

int main()
{
    func();
    deriv();
}

I have a more difficult example that I am working on and was trying to make it as close as possible. Can I, in this case use the Struct result only once to divide the function and its Derivative into two functions?

If I call Struct result twice in func() and deriv(), it calculates the function cof() twice which makes it take longer. I would like to avoid that.

1

There are 1 answers

0
chux - Reinstate Monica On

If I call Struct result twice in func() and deriv(), it calculates the function cof() twice which makes it take longer. I would like to avoid that.

Code needs to share the value stored in result between the 2 functions: func() and deriv().

A simple approach is to pass a pointer the structure to the 2 functions so they share that data.

void func(Struct *result_ptr) {
    //Struct result;

    // result = cof();
    *result_ptr = cof(); // Save the result in location provided.
    ...

}

void deriv(Struct *result_ptr) {
    // Struct result;
    // result = cof();
    // dxda = result.dxda;
    dxda = result_ptr->dxda;  // Use the result passed in.
    ...
}

int main() {
    //func();
    //deriv();
    Struct result = { 0 };
    func(&result);
    deriv(&result);
}

Tip: weak object naming and missing free() obfuscates the key issue. OP needs to improve that too.