This question already has answers here:
Assigning Float Pointers in C [closed]
                                
                                    (3个答案)
                                
                        
                                6年前关闭。
            
                    
我是C语言的新手,我正在编写一个非常基本的函数,该函数将整数指针作为参数。在函数内部,必须创建一个浮点指针。此函数必须将整数指针的值分配给浮点数,然后返回浮点数。这是我目前的代码:

float * function(const int *x)
{
    float *p = (float*)x;
    return p;
}


但这会导致运行时读取如下错误:“ free():无效指针:0x00007fffc0e6b734”。可以说,我很困惑。您能提供的任何见解将不胜感激!

最佳答案

对C陌生,您对scope of variables熟悉吗?变量作用域的简短版本(的一部分)是,如果您不做任何额外的操作,则在函数中创建的变量仅存在于该函数内部。为什么这对您很重要:如果您返回指向在函数内部创建的变量的指针(不做任何额外的事情),则该指针将指向可能包含或可能不包含分配给它的值的内存区域。一种执行所需操作的方法是:

float *makefloat(int *x) {

//  static keyword tells C to keep this variable after function exits
    static float f;

//  the next statement working from right to left does the following
//  get value of pointer to int (x) by dereferencing:   *x
//  change that int value to a float with a cast:       (float)
//  assign that value to the static float we created:   f =
    f = (float) *x;
//  make pointer to float from static variable:         &f
    return &f;
}


通常,我似乎看到更多的函数接受指向要修改的变量的指针,然后在该函数中创建新值并将其分配给该指针所引用的内存区域。因为该内存区域不在函数范围之内,所以不必担心范围和静态变量。关于静态变量的另一个很酷的事情是,下次调用该函数时,该静态变量的值与上次退出该函数时的值相同。在Wikipedia上解释。

*&的良好解释:Pointers in C: when to use the ampersand and the asterisk

关于c - C中的类型转换指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21419439/

10-11 22:55
查看更多