Possible Duplicate:
How to modify content of the original variable which is passed by value?
I am building a
You need to assign the return value of FindArea
to rArea
. At the moment, FindArea
assigns the product to its local variable of the same name.
Alternatively, you can pass the address of main
's rArea
to modify that, that would look like
FindArea(&rArea, rBase, rHeight);
in main
with
void FindArea(int * rArea, int rBase, int rHeight) {
*rArea = rBase * rHeight;
}
take rArea
by pointer:
int FindArea(int *, int , int);
...
FindArea (&rArea , rBase , rHeight);
...
int FindArea (int *rArea , int rBase , int rHeight)
{
*rArea = (rBase * rHeight);
return (*rArea);
}
Your basic problem is you don't understand how to get values out of a function. Change the relevant lines to:
int FindArea(int rBase, int rHeight); // prototype
and
int area = FindArea(rBase, rHeight);
and
int FindArea(int rBase, int rHeight)
{
return rBase * rHeight;
}
Because you are not storing the return value. The code won't compile in its present form.
Call it as:
rArea = (rBase , rHeight);
Change the function to:
int FindArea (int rBase ,int rHeight)
{
return (rBase * rHeight);
}
Change the prototype to:
int FindArea(int , int);
FindArea (rArea , rBase , rHeight);
doesn't work like you think it does. In C, parameters are passed by value; that means modifying area
inside the function modifies only a local copy of it. You need to assign the return value of the function to the variable:
int FindArea(int w, int h) { return w * h; }
int w, h, area;
// ...
area = findArea(w, h);
You intialize rArea
to 0. Then, you pass it into FindArea
by value. This means none of the changes to rArea
in the function are reflected. You don't make use of the return value, either. Therefore, rArea
stays 0.
Option 1 - Use the return value:
int FindArea(int rBase, int rHeight) {
return rBase * rHeight;
}
rArea = FindArea(rBase, rHeight);
Option 2 - Pass by reference:
void FindArea(int *rArea, int rBase, int rHeight) {
*rArea = rBase * rHeight;
}
FindArea(&rArea, rBase, rHeight);