Solution for Exercise 03_07-both.c

03_07-both.c

#include <stdio.h>

int *both(int *a)
{
	/* output the value at a */
	printf("Value passed: %d\n",*a);
	/* double the value */
	*a *= 2;
	/* return the same address */
	return(a);
}

int main()
{
	int x,*y;
   
	x = 100;
	y = both(&x);
	printf("Value returned: %d\n",*y);

	return 0;
}

Output

Value passed: 100
Value returned: 200

Notes

* In the main() function, both variable x and pointer y are declared as integers: int x,*y;

* From the main() function, the value of variable x is passed to the both() function: y = both(&x);

* The both() function immediately outputs the value of variable a. Then the value is doubled: *a *= 2;

* The pointer need not be returned. After all, the value of a is already altered. In fact, you could declare a pointer inside the both() function and return its value (which is a bit more complicated), but returning the address of a is good enough.

*If you wanted to use a pointer variable in the both() function, and not just modify the passed variable a, remember to declare it static so that it's address isn't lost after the function ends.

* In the main() function, the value returned from both() is saved in pointer variable y. At this point in the code, both variables x and y have the same address and the same value. For the final printf() statement, you could use either *y or x to get the same result.