【发布时间】:2014-10-28 16:14:54
【问题描述】:
考虑一下这个小代码
#include <stdio.h>
#include <stdlib.h>
void* foo1(double bar)
{
double s2 = 0.5;
double s1 = bar/s2;
double toreturn[2] = {s1,s2};
printf("Outside main. Second value: %f\n", toreturn[1]); //this line is commented out for the second output. See below text
return toreturn;
}
int main()
{
void* (*foo)(double) = NULL;
foo = &foo1;
double bar = 2.12;
double* resp = foo(bar);
printf("In main. First value: %f\n", resp[0]);
printf("In main. Second value: %f\n", resp[1]);
return 0;
}
代码输出
Outside main. Second value: 0.500000
In main. First value: 4.240000
In main. Second value: 0.500000
,这正是我所期望的。但是,如果我注释掉打印指令(foo1 定义中的指令),我会得到以下输出:
In main. First value: 4.240000
In main. Second value: 0.000000
,这对我来说毫无意义!对我来说,printf 命令可以更改变量的值似乎很奇怪。你能解释一下请解释一下这种行为吗?
【问题讨论】:
-
尝试 %lf 而不是 %f
-
另外,toreturn 是函数返回时消失的局部变量。
-
@Charlie Burns 注意:
printf()的double或float打印与说明符"%lf"或"%f"相同。 -
那一定是新的......就像在过去 20 年内一样。是因为浮点数在参数列表中被提升为双精度数吗?
标签: c function pointers printf