c - printf函数会影响变量的生命周期吗?

标签 c pointers printf

这是我的简单 C 程序。

#include <stdio.h>
float*multiply(int, float);

main(){
   int i =3;
   float f = 3.50, *p;
   p = multiply(i, f);
   printf("%u\n", p);
   printf("%f\n", *p);
   return 0;
}

float *multiply(int ii, float ff){
   float product = ii * ff;
   printf("%f\n", product);
   printf("%u\n", &product);
   return (&product);
}

该程序给出以下输出:-

enter image description here

但是,当我注释掉 multiply 函数中的两个“printf”语句时,它给出以下输出:-

enter image description here

我确信我没有犯任何愚蠢的错误。我只是注释掉两行。 谁能告诉我为什么会发生这种情况?这是操作系统/系统相关的问题吗? printf 函数如何延长变量的生命周期?

最佳答案

您正在返回本地基于堆栈的变量product的地址,这将导致未定义的行为。

此外,要打印指针的值,应使用 %p 而不是 %uhttp://www.cplusplus.com/reference/cstdio/printf/

关于c - printf函数会影响变量的生命周期吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25268753/

相关文章:

c - 在 C 中使用 while() 测试不等式

c - 读取数据可能未对齐的 WAV 文件

C编程输入错误

c - 为什么 '+' 符号不能与 printf 一起用于无符号值?

c - 简单的C题

c - 将名称添加到多重链接列表中

c - 我如何获得这个地址?

c - 在 C 中传递给函数 arg 时结构指针和结构之间的区别

c++ - 如何使用智能指针构建树?

c++ - 如何从 C/C++ 中的以下函数获取所有参数?