printf 更改值

Rem*_*i.b 1 c printf pointers function

考虑这个小代码

#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;
}
Run Code Online (Sandbox Code Playgroud)

代码输出

Outside main. Second value: 0.500000
In main. First value: 4.240000
In main. Second value: 0.500000
Run Code Online (Sandbox Code Playgroud)

,这正是我所期望的。但是,如果我注释掉打印指令(定义中的指令foo1),我会得到以下输出:

In main. First value: 4.240000
In main. Second value: 0.000000
Run Code Online (Sandbox Code Playgroud)

,这对我来说毫无意义!一个printf命令可以改变变量的值对我来说似乎很奇怪。你能解释一下请解释我这种行为吗?

afe*_*ter 5

这里的要点是您不能从函数返回本地数组。toreturn函数调用后,数组使用的内存是空闲的。它可以被任何函数调用覆盖,包括printf.

使用malloc以在功能的阵列分配内存,并返回一个指向所分配的内存,或通过数组作为参数。