-1

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);
} 
Tordek
  • 10,628
  • 3
  • 36
  • 67
Siavash
  • 3
  • 2

2 Answers2

1

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.

Tordek
  • 10,628
  • 3
  • 36
  • 67
  • Thx but could you tell me why this works without returning pointer to the results and heaping? #include void* square (const void* num); int main() { int x, sq_int; x = 6; sq_int = square(&x); printf("%d squared is %d\n", x, sq_int); return 0; } void* square (const void *num) { int result; result = (*(int *)num) * (*(int *)num); return result; } – Siavash Nov 17 '19 at 21:02
  • @Siavash: when you declare a variable, it's stored in the stack; when the funcion returns, the stack pointer is moved back, so it's effectively "freed". If you use the contents of the variable after returning from the function, it's possible for another function to overwrite that value. It isn't the case here, since your program is simple, but in general it's not a good idea. – Tordek Nov 17 '19 at 23:49
0

You need to do two things.

Cast the return type:

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

Return the address of result.

return &result;
klutt
  • 30,332
  • 17
  • 55
  • 95
  • Thx for your answer but still this way doesn't work. – Siavash Nov 17 '19 at 20:52
  • @Siavash Define "work". For me it returns the squared number, which is to be expected judging from the name `square`. – klutt Nov 17 '19 at 20:56
  • I'm using codeblock for compiling c codes but after running this way the program crashes! I tried it on free C the same happens there. – Siavash Nov 17 '19 at 21:06
  • @Siavash Don't know what to say. It compiles without warnings for me with `gcc` and I cannot see any reason why it should not work. – klutt Nov 17 '19 at 21:09