谁能用C语言解释一下这段小代码?

标签 c

输出是:

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)
int35.2 被截断为 30,结果为
60 而不是 60.2

关于谁能用C语言解释一下这段小代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59184245/

相关文章:

java - 我想编写一个可以在另一个程序中运行和执行操作的程序

c++ - 指针数组和指向指针数组的指针

c++ - 是否有适用于新 C++ 的 cfront 工具?

c - C++11 中的 async-future 模型或 C# 中的 async-await 有什么好的 C 实现吗?

c++ - 使用 av_read_frame() 获取 2 个连续帧

c - 无法在 Raspberry Pi 上加载 eBPF/XDP 代码

c - 为什么 Linux 内核无锁链表有 head 和 node 结构?

java - Java 中的链接错误

c - 为什么连续数组元素的地址在这里递增四?

c++ - 在没有 ncurses 的 C/C++ 中编写 "real"交互式终端程序,如 vim、htop、...