#include<stdio.h>
int g(int *a, int *b);
int main()
{
int a = 2;
int b = 7;
b = g(&b , &a);
printf("a = %d\n", a);
printf("b = %d\n", b);
return 0;
}
int g(int *a, int *b)
{
(*a) = (*a) + 3;
(*b) = 2*(*a) - (*b)+5;
printf("a = %d, b = %d\n", *a, *b);
return (*a)+(*b);
}
The output is:
a = 10, b = 23
a = 23
b = 33
I'm in an Intro to C programming class and having trouble understanding how this works.
Thanks for the help!
Sequencing the events as presented in question:
int main() {Declaration of
aandband value assignment:int a = 2; int b = 7;
Here is a trick, the address passed to the parameter
int* ais actually ofb, and vice-versa on the second parameter:b = g(&b , &a);
Here just printing values of
aandb:printf("a = %d\n", a); printf("b = %d\n", b); return 0; }
Since the parameters are pointers, the changes made, in the scope of this function, to the variable addresses pointed by them are permanent:
int g(int *a, int *b) {
Here, dereferencing the pointer (
*a, the parentheses are not needed in these cases), means you are now working with the value stored in the address pointed bya, so7 + 3 = 10, now the value stored in the address pointed byais= 10:(*a) = (*a) + 3;
Here, the same thing, dereferencing pointers, so
2 * 10 - 2 + 5 = 23, the value stored in the address pointed bybwill be23:(*b) = 2*(*a) - (*b)+5;
Here printing
a = 10andb = 23, again, dereferencing pointers means you are working with the values stored in the addresses pointed by them:printf("a = %d, b = %d\n", *a, *b);
The returned value is
10 + 23 = 33, so forb = g(&b, &a),bwill be assigned the value of33,ais already23so it stays that way:return (*a)+(*b); }
Remember that C passes all function arguments by value - that means that the formal parameter in the function body is a separate object in memory from the actual parameter in the function call, and the value of the actual parameter is copied to the formal parameter.
For any function to modify the value of a parameter, you must pass a pointer to that parameter:
void foo( T *ptr ) // for any type T
{
*ptr = new_T_value(); // write a new value to the thing ptr points to
}
void bar( void )
{
T var;
foo( &var ); // write a new value to var
}
In the code above, all of the following are true:
ptr == &var
*ptr == var
Thus, when you write a new value to the expression *ptr, it's the same as writing a new value to var.
I think part of what's making this confusing for you is that the names of your formal parameters (a and b) and your pointers (a and b) are flipped - g:a points to main:b and vice versa.
g:a == &main:b // I'm using g: and main: here strictly to disambiguate
*g:a == main:b // which a and b I'm talking about - this is not based on
// any real C syntax.
g:b == &main:a
*g:b == main:a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With