使用指针将值从 scanf() 传递到 main()

Using pointers to pass a value from scanf() into main()

下面的代码工作正常。它允许用户输入一个名为 errorfloat 值,通过 function error_user();

保存它
#include <stdio.h>
#include <stdlib.h>


float error_user ();

int main(void)
{
    float error;

    printf("What error do you want?\n");

    error=error_user ();

    printf("%f\n", error);

    return 0;
}

float error_user ()
{
    float error;
    scanf("%f", &error);
    return error;
}

但是,下面的功能不起作用。我试图获得相同的结果,唯一的区别是我想用指针传递值。在第二种情况下我怎样才能做到这一点?谢谢!

#include <stdio.h>
#include <stdlib.h>

void error_user (float *error);

int main(void)
{
    float error;

    printf("What error do you want?\n");

    error_user (&error);

    printf("%f\n", error);

    return 0;
}

void error_user (float *error)
{
    scanf("%f", &error);
}

下面是基于@John Bode 的更正代码。转述他:"In the second version, error already has type float *, so you don’t need to use the & operator in the scanf call."

#include <stdio.h>
#include <stdlib.h>

void error_user (float *error);

int main(void)
    {   
        float error;

        printf("What error do you want?\n");

        error_user (&error);

        printf("%f\n", error);

        return 0;
    }

void error_user (float *error)
    {   
        scanf("%f", error);
    }

由于在第二个示例中,error 的类型为 float *,因此 error_user 中的 scanf() 调用中的转换说明符和相对参数之间存在类型不匹配函数,如果你使用 &error.

&errorfloat** 类型,但 %f 转换说明符需要一个 float*.

类型的参数

提供错误类型的参数调用 undefined behavior.

使用 error 而不是 &error


编译器通常会在没有调用额外的编译器标志的情况下警告您这个问题。例如 gcc:

"warning: format '%f' expects argument of type 'float *', but argument 2 has type 'float **' [-Wformat=]"

您应该将编译器更新或更换为符合标准的编译器,或者停止忽略编译器警告。