Question

Having an issue with pointers and functions. #include <stdio.h> int f(int *a, int *b); int main()...

Having an issue with pointers and functions.

#include <stdio.h>

int f(int *a, int *b);

int main()

{
int a = 2, b = 7;
b = f(&b, &a);
printf("a = %d,\n", a);
printf("b = %d\n", b);
return 0;
}
int f(int* a, int* b) {
    (*a) = (*a) + 3;
    (*b) = 2*(*a) - (*b)+5;
    printf("a = %d b = %d\n", *a, *b);
    return(*a)+(*b);

}

can someone explain to me why the output is

a = 10 b =23

a = 23

b = 33

I understand that (&b, &a) flips the numbers in the function but why does b = 23 and not 13 ?

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Ans :

int main()

{
int a = 2, b = 7;
b = f(&b, &a);
printf("a = %d,\n", a);
printf("b = %d\n", b);
return 0;
}

in that function initailly value of a=2 and b=7

and when we calling the function f(&b, &a); we are passing the reference of the variable. It is call by reference type function. inside that function we are passing the address of the variable a and b.

so in the first arguement we are passing reference(address) of b and in the second arguement, address of a is passed.

  Inside the function f

int f(int* a, int* b) {
    (*a) = (*a) + 3;
    (*b) = 2*(*a) - (*b)+5;
    printf("a = %d b = %d\n", *a, *b);
    return(*a)+(*b);

}

we are getting the address of b into a and address of a into b.

So here address of variable in the memory are flipped.

In that function currently a is holding value 7 and b is holding value 2.

in the expression     (*a) = (*a) + 3; will be evaluated as (*a)=7+3=10;

so value of (*a) is 10.

In the next expession (*b) = 2*(*a) - (*b)+5; here (*b)=2

=> (*b) = 2 * 10 - 2 +5 =23

so    printf("a = %d b = %d\n", *a, *b); will print    a =10 b =23. inside the function these are local variable for the function.

This statement return(*a)+(*b) will return 10 +23=33

So  return(*a)+(*b); will return 33

and that value is hold by b in the main function b = f(&b, &a); so here value of b will became 33.

and value of a will became 33.

Handwritten detailed solution :

Add a comment
Know the answer?
Add Answer to:
Having an issue with pointers and functions. #include <stdio.h> int f(int *a, int *b); int main()...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT