I need help solving this problem in my mind so if anyone had a similar problem it would help me.
For example:
Enter: 2 3
Output: 4199120/3436544
It should print: 2/3
Why is the output different from what I expect?
struct Fraction { int x1, x2; };
void function(struct Fraction p, int *d) {
p.x1=d[0];
p.x2=d[1];
}
int main() {
struct Fraction frac;
int d[2];
for(int i=0;i<2;i ) {
scanf("%d", &d[i]);
}
function(frac, d);
printf("%d/%d", frac.x1, frac.x2);
return 0;
}
CodePudding user response:
You are passing frac
by value to function
(the link explains why exactly the parameter is not modified). Try:
void function(struct Fraction *p, int *d) {
p->x1=d[0];
p->x2=d[1];
}
int main() {
...
function(&frac, d);
printf("%d/%d", frac.x1, frac.x2);
return 0;
}
CodePudding user response:
Always pay attention to your compiler warnings.
main.c: In function ‘main’:
main.c:21:1: warning: ‘frac.x2’ is used uninitialized in this function [-Wuninitialized]
21 | printf("%d/%d",frac.x1,frac.x2);
Your compiler tells you that the frac
is uninitialized. Why? The function
was supposed to initialize it, i.e., fill it with data.
However, you are passing it by value to your function
. Your function
, when executed, creates a brand new struct Fraction
, copies the contents of frac
that you have passed, then does what you expect it to do; fills its own struct Fraction p
, with d[0]
and d[1]
and returns, deleting the local variable struct Fraction p
with it.
The printf
in the main simply prints the garbage that was in the frac
to begin with.
Your function
should modify the actual variable frac
local to main, hence you need to pass the address of it as:
function( &frac, d );
And of course the function
should accept it as such:
void function(struct Fraction *p, int *d)
{
p->x1 = d[0];
p->x2 = d[1];
}
CodePudding user response:
One other option is to return a struct from the function
struct Fraction function(int *d) {
struct Fraction res;
res.x1 = d[0];
res.x2 = d[1];
//int gcd = calc_gcd(d[0], d[1]); // calc_gcd() calculates the greatest common denominator
// implementation left as an exercise
//rec.x1 /= gcd;
//rec.x2 /= gcd;
return res;
}
And then your code would be
int main(void) {
struct Fraction frac;
int d[2];
for(int i = 0; i < 2; i ) {
scanf("%d", &d[i]); // error checking ommited for brevity
}
frac = function(d);
printf("%d/%d\n", frac.x1, frac.x2);
return 0;
}