C 中的类型转换指针 [英] Typecasting Pointers in C

查看:76
本文介绍了C 中的类型转换指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C 的新手,我正在编写一个非常基本的函数,它将整数指针作为参数.在函数内部,必须创建一个浮点指针.此函数必须将整数指针的值分配给浮点数,然后返回浮点数.这是我目前的代码:

I'm new to C, and I'm writing a very basic function that takes an integer pointer as a parameter. Inside the function, a float pointer must be created. This function must assign the value of the integer pointer to the float and then return the float. Here's my code at the moment:

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

但这会导致运行时出现错误:free(): invalid pointer: 0x00007fffc0e6b734".我只想说,我很困惑.您能提供的任何见解将不胜感激!

But this results in an error that reads as such when run: "free(): invalid pointer: 0x00007fffc0e6b734". Suffice it to say, I'm very confused. Any insights you can offer would be much appreciated!

推荐答案

作为 C 的新手,您是否熟悉 变量范围?(部分)变量作用域的简短版本是,如果你不做一些额外的事情,在函数中创建的变量只存在于该函数内部.为什么这对您很重要:如果您返回一个指向您在函数中创建的变量的指针(没有做一些额外的事情),该指针将指向一个内存区域,该区域可能包含也可能不包含您分配给它的值.做你想做的一种方法是这样的:

Being new to C, are you familiar with the scope of variables? (Part of) the short version of variable scope is that if you don't do a little something extra, a variable created in a function only exists inside that function. Why that's important to you: if you return a pointer to a variable that you created inside a function (without doing that little something extra) that pointer will point to an area of memory that may or may not contain the value that you assigned to it. One way to do what you want is this:

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;
}

总的来说,我似乎看到更多的函数接受指向要修改的变量的指针,然后在该函数中创建新值并将其分配给指针引用的内存区域.由于该内存区域存在于函数作用域之外,因此无需担心作用域和静态变量.关于静态变量的另一个很酷的事情是,下次调用函数时,静态变量的值与函数上次退出时的值相同.在维基百科上进行了解释.

In general I seem to see more functions that accept a pointer to the variable that is to be modified, then in that function the new value is created and assigned to the area in memory referenced by the pointer. Because that area of memory exists outside of the scope of the function, there is no need to worry as much about scope and static variables. Another cool thing about static variables is that the next time the function is called, the static variable has the same value it did when the function last exited. Explained on Wikipedia.

*& 的很好解释:C 中的指针:when使用与号和星号

这篇关于C 中的类型转换指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆