在C中分配浮点指针

use*_*411 -1 c pointers

我目前拥有的是一个简单的函数,基本上只是在给定参数指针的情况下重新分配指针,但是我收到一条错误,说我正在使用其中一个未初始化的变量.这就是我所拥有的,错误是在线上抛出*x =*k;

float * program(const int *k)
{
    float *x;
    *x = *k;
    return x;
}
Run Code Online (Sandbox Code Playgroud)

这必须是一个非常简单的修复,但我觉得我只是错过了它.

Erg*_*wun 5

这是您的代码正在做的事情:

float * program(const int *k)
{
    // declare a pointer to a float, but don't initialize it,
    // so it is not actually pointing anywhere specific yet.
    float *x; 
    // Put the value pointed at by k into the location pointed at by x
    // But wait - we don't know where x is pointing, so this is BAD!
    *x = *k;
    return x;
}
Run Code Online (Sandbox Code Playgroud)

这就是你的编译器抱怨的原因.