Solution for Exercise 03_04-added.c
03_04-added.c
#include <stdio.h>
void added(int *a, int *b)
{
*b = *a * 2;
}
int main()
{
int x,y;
x = 22;
added(&x,&y);
printf("%d doubled is %d\n",x,y);
return 0;
}
Output
22 doubled is 44
Notes
* Obviously, your solution need not look exactly like what's shown above.
* The added() function requires two pointer arguments, which I define as a and b.
* The value of a (written as *a) is doubled: *a * 2
* The compiler is smart enough to know the difference between the * pointer operator, which binds tightly to variable a, and the * multiplication operator.
* The result of *a * 2 is stored at the address in pointer variable b.
* No value needs to be returned from the added() function as the value generated is stored directly in memory and accessed from the main() function.
* In the main() function, I use integer variables x and y. Variable x is assigned the value 22: x = 22;
* The addresses of variables x and y are passed to the added() function: added(&x,&y). The & operator satisfies the function's desire for pointers/addresses.
* Variable y isn't initialized when it's passed to the added() function. This condition is unacceptable for a pointer variable, but for a non-pointer variable like y it's tolerable. Because I know that the added() function doesn't use any garbage value already stored in memory, it's okay. Always be aware when passing uninitialized variables to a function.
Copyright © 1997-2025 by QPBC.
All rights reserved
