I’ve struggled with the same issue, and may have attempted a similarly super wrong and horribly ugly hack - so in an effort to limit the number of times this is asked (and hopefully answered), here are the details of my troubles:
Attempt 1 (the following lines represent the only change to the main function in ex22_main.c - no other files have been changed from the provided source in the book):
// Try to access ratio
double *ratio = &(update_ratio(1.0));
log_info("ratio is %f", ratio);
This results in the following error:
ex22_main.c:51:21: error: lvalue required as unary ‘&’ operand
My suspicion is that this approach couldn’t hope to work because update_ratio, as defined in ex22.c, is just returning a constant double value (for this invocation of the function anyway)… an rvalue rather than the expected lvalue.
Attempt 2 changes a bunch:
in ex22.c:
double *update_ratio(double new_ratio) {
static double ratio = 1.0;
double old_ratio = ratio;
ratio = new_ratio;
return &old_ratio;
}
and in ex22_main.c (in the main function):
// Try to access ratio
double *ratio = update_ratio(1.0);
log_info("ratio is %f", *ratio);
Result:
[amartinez@titanium ex22]$ cc -Wall -g -DNDEBUG -c -o ex22.o ex22.c && cc -Wall -g -DNDEBUG
ex22_main.c ex22.o -o ex22_main
ex22.c: In function ‘update_ratio’:
ex22.c:24:12: warning: function returns address of local variable [-Wreturn-local-addr]
return &old_ratio;
^~~~~~~~~~
Along with a segfault on execution. This is also not the right way to break it, though broken it certainly is. My hope was that I’d be able to get at the actual value of ratio from inside update_ratio, but that doesn’t appear to be the case.
At any rate, I’ve exhausted my attempts at Google/StackOverflow, manpages, and gdb. If anyone can shed some light down the right path I’d appreciate it, as I’m sure the OP would as well.