+ 2

How does this code work?

void fun(int* i, int* j) { *i = *i * *i; *j = *j * *j; } int main() { int i = 2, j = 3; fun(&i, &i); printf("%d, %d", i, j); return 0; } Got this in sololearn challenge. Output was 16,3. How does this work? I thought the answer would be 4,9. https://code.sololearn.com/cGrWtuvxOrbO/?ref=app

29th Oct 2019, 6:35 AM
Dhawal Mehta
Dhawal Mehta - avatar
3 ответов
+ 4
The output 16, 3 was because you pass the address of <i> (in main) as argument for both <i> and <j> parameter of `fun()` function. `fun(&i, &i);` // <= this line So the variable <j> is left unharmed here because you didn't pass it in as argument to function `fun`. Let's see what happens in `fun` function. Remember we passed address of <i> as argument for both <i> and <j> parameter when we invoke `fun` function. ● Initially: *i = 2, *j = 2 // both points to same variable, that is <i> in `main` function. *i = *i * *i; // *i = 2 * 2 => 4 // parameter <j> is actually the same with parameter <i>. // So here we are actually changing same variable through the address. *j = *j * *j; // *j = 4 * 4 => 16 ● Return to main function: <i> is now 16 because its value was changed inside `fun`. Hth, cmiiw
29th Oct 2019, 7:28 AM
Ipang
+ 3
I'm glad, was afraid because I didn't feel it was clear enough 😁
29th Oct 2019, 7:40 AM
Ipang
+ 2
Ipang Thanks! Well explained! I understood it now.
29th Oct 2019, 7:36 AM
Dhawal Mehta
Dhawal Mehta - avatar