简体   繁体   English

如何将 void 指针转换为要在 C 中的 function 中使用的浮点数?

[英]How to cast a void pointers to float to be used in a function in C?

I changed a code so that it could accept floats in a void pointer cast and use it in a function but while it was working with ints before making adjustment to it made the "incompatible types when assigning to type 'float' from type 'void *'" after I changed it to floats, could some one help where am I making a mistake?我更改了一个代码,以便它可以接受 void 指针转换中的浮点数并在 function 中使用它,但是在对其进行调整之前使用整数时,在从类型 'void * '" 在我将其更改为浮点数之后,有人可以帮助我在哪里犯错吗?

#include <stdio.h>

void * square (const void *num);

int main() {
  float x, sq_int;
  x = 6.543;
  sq_int = square(&x);
  printf("%f squared is %f\n", x, sq_int);
  return 0;
}

void* square (const void *num) {
  static float result;
  result = (*(float *)num) * (*(float *)num);
  return(result);
} 

The problem line is问题线是

sq_int = square(&x);

because square returns void* as well.因为square也返回void*

You need to handle the return of square either by returning a pointer to the result, like您需要通过返回指向结果的指针来处理square的返回,例如

return &result;

and in main extract it as:并主要将其提取为:

sq_int = *(float *)square(&x);

Which is a bad idea since you're accessing a variable that is no longer on the stack.这是一个坏主意,因为您正在访问一个不再在堆栈上的变量。


Or better, by storing it in the heap first, like或者更好的是,首先将其存储在堆中,例如

void* square (const void *num) {
  float *result = malloc(sizeof(float));
  *result = (*(float *)num) * (*(float *)num);
  return result;
} 

and in main extract it as:并主要将其提取为:

sq_int = *(float *)square(&x);

But do remember to free up the allocation before exiting.但请记住在退出之前释放分配。

You need to do two things.你需要做两件事。

Cast the return type:转换返回类型:

sq_int = *(float*) square(&x);

Return the address of result .返回result地址

return &result;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM