In C, passing by address and modifying in-place: what does this program print? #include<stdio.h> void fun(int*, int*); int main() { int i = 5, j = 2; fun(&i, &j); printf("%d, %d", i, j); return 0; } void fun(int *i, int *j) { *i = *i * *i; *j = *j * *j; }

Difficulty: Easy

Correct Answer: 25, 4

Explanation:


Introduction / Context:
This tests basic C pointer usage with pass-by-address. When you pass addresses and dereference inside the callee, you can modify the caller’s variables directly.



Given Data / Assumptions:

  • i = 5, j = 2 in main.
  • Call: fun(&i, &j);
  • In fun, both pointed-to values are squared.


Concept / Approach:
Since the function parameters are pointers, *i and *j refer to the original variables. Reassigning them updates the caller’s variables.



Step-by-Step Solution:
Before call: i = 5, j = 2.Inside fun: *i = *i * *i → 25 and *j = *j * *j → 4.After fun returns, i is 25 and j is 4.Printed output: “25, 4”.



Verification / Alternative check:
Replacing pointer parameters with return values would require returning two values (e.g., via a struct). Pointers allow both updates in one call.



Why Other Options Are Wrong:
“5, 2” reflects no change. “10, 4” incorrectly squares only one operand. “2, 5” swaps and changes meaning. “25, 2” squares only i.



Common Pitfalls:
Forgetting to pass addresses; confusing *i * *i with dereferencing precedence (it is simply the product of the dereferenced value with itself).



Final Answer:
25, 4

More Questions from Functions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion