How do I get a function to modify any of the param

2019-03-04 02:38发布

问题:

My objective:

I have to create a function which adds up two fractions.

I've defined a new struct (typedef) called fraction.

The function can't have a return type fraction, it has to be void, therefore it has to modify one of the parameters entered, how can I achieve this? Pointers maybe? How would you modify my code to achieve it?

This is my code:

typedef struct{
    char sign;
    int num;
    int den;
} fraction;

void sum(fraction, fraction, fraction);

int main(void) {

    fraction op1, op2, solution;

    sum(op1, op2, solution);

    return 0;
}

void sum(fraction f1, fraction f2, fraction sol){

    if (f1.sign == '-') {
        f1.num = f1.num * -1;
    }

    if (f2.sign == '-') {
        f2.num = f2.num * -1;
    }

    sol.num = f1.num*f1.den + f2.num*f1.den;
    sol.den = f1.den * f2.den;
    sol.sign = '+';

    if (sol.num < 0) {
        sol.sign = '-';
        sol.num = sol.num * -1;
    }
}

回答1:

This is generally a bit broad, but to show you the pointers, let me add, yes, you're on correct path.

Pointers maybe?

Yes. To elaborate on the why part :

C uses pass-by-value for function argument passing, so, you cannot modify an argument from inside a called function and expect that value to be retained / reflected in the caller. However, if we pass a pointer as an argument, the pointer itself cannot be modified from the called function as stated above, but any change made to the memory location pointed to the pointer, will be reflected in the caller (as long as the pointer is valid, per se).

Now, coming to the how part:

You need to pass the third argument (or, whichever that is supposed to store the result) as a pointer to the structure variable. This way, modifications to the memory location pointed to by the address, inside the called function will be reflected in the caller.

So, your function signature will look like

 void sum(fraction f1, fraction f2, fraction * sol)

and the function call will look like

 sum(op1, op2, &solution);

Now, the access to sol inside the called function, I leave to you.