我是 C 新手,正在编写一个非常基本的函数,该函数采用整数指针作为参数。在函数内部,必须创建一个浮点指针。该函数必须将整数指针的值赋给浮点型,然后返回该浮点型。这是我目前的代码:
float * function(const int *x)
{
float *p = (float*)x;
return p;
}
但这会导致运行时出现这样的错误:“free(): invalid point: 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/