简体   繁体   中英

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?

#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.

You need to handle the return of square either by returning a pointer to the result, like

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 .

return &result;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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