输出是:
25
28ff1c
28ff1c
25
我不明白为什么。第一个值和地址都可以理解,但是为什么第二个输出是一样的呢?函数中g的地址没有改变吗?
float add(int *x, int y)
{
static float s = 100.f;
s=s+y;
x=x+y;
return s;
}
int main()
{
int g=25;
printf("%d\n",g);
printf("%x\n",&g);
add(&g,35.2);
printf("%x\n",&g);
printf("%d\n",g);
return 0;
}
最佳答案
...但是为什么第二个输出是相同的?
因为你的原始代码:
float add(int *x, int y)
{
static float s = 100.f;
s=s+y;
x=x+y; // changing the pointer
return s;
}
不改变x地址指向的值。
更改所示代码以允许更新值:
float add(int *x, int y)
{
static float s = 100.f;
s=s+y;
*x=*x+y; //changing the value pointed to by the pointer
//(i.e., the value exposed via the de-referenced pointer is
//modified to a new value.)
return s;
}
给定:
int g=25;
...
add(&g,35.2);
更改后的结果:
25
81feb8
81feb8
60
注意:因为第二个参数的类型:float add(int *x, int y)
为 int
,35.2
被截断为 30
,结果为
60
而不是 60.2
关于谁能用C语言解释一下这段小代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59184245/