Variant 1 doesn’t work, and the reason why is that the arguments ftPtr and inPtr in your function (defined as variables, not pointers) only exist while the function is executing; the second the function completes those variables (arguments = variables) cease to exist. Running variant 1 returns 0 feet and 0 inches.
This is the whole purpose of “pass by reference”, it is a way of having functions return values to a calling routine by storing the contents in variables that had been declared in the calling routine, and it is done by using pointers to those variables.
As for your questions with variant 2 and modf():
- The reason ftPtr works is that it is an address you are sending modf() (it is defined as *ftPtr in your function argument, which means it is a pointer), and that is what modf() expects.
- The reason you need to use *inPtr is that modf() is returning a value, so you need to dereference inPtr as it is a pointer as defined in your function argument. A pointer stores an address, not a value.
Hope this helps…Ian
[quote=“burkanov”]Hello,
as for the challenge in chapter 10, I’m not sure which way is better:
[size=150]variant 1[/size]
to call the function passing variables
[code]void metersToFeetAndInches(double meters, double ftPtr, double inPtr){
double rawFeet = meters * 3.281;
inPtr = modf(rawFeet, &ftPtr) * 12.0;
}
int main(int argc, const char * argv[])
{
double meters = 3.0;
double feet;
double inches;
metersToFeetAndInches(meters, feet, inches);
printf("%.1d meters is equal to %.1d feet and %.3f inches.\n", (int)meters, (int)feet, inches);
return 0;
}[/code]
or
[size=150]variant 2[/size]
to pass their addresses only and declare new pointers in function’s params. By the way, though this version works as well, I’m still still unsure why the second parameter in modf should be ftPtr, but the results of modf are assigned to *inPtr. The only explanation I see, is that the ftPtr in this case represents (somehow) an address, which is required by modf, while the fraction part is assigned to *inPtr (and I don’t have a clue why we should write it with asterix - it’s already declared as a pointer in the function’s params, right?)… So, the code is working, but still many questions why
[code]void metersToFeetAndInches(double meters, double *ftPtr, double *inPtr){
double rawFeet = meters * 3.281;
*inPtr = modf(rawFeet, ftPtr) * 12.0;
}
int main(int argc, const char * argv[])
{
double meters = 3.0;
double feet;
double inches;
metersToFeetAndInches(meters, &feet, &inches);
printf("%.1d meters is equal to %.1d feet and %.3f inches.\n", (int)meters, (int)feet, inches);
return 0;
}[/code][/quote]