Search code examples
cfunctionpointersreturn

Returning float in void* function


I'm learning how pointers works, but I don't understand one thing in this code. Returning int in void* function works like a charm, but returning float does'nt.

#include <stdio.h>

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;
}
#include <stdio.h>

void* square (const void* num);

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

  return 0;
}

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

Solution

  • If you still want to want this to work, you should return a pointer to a float. But doing this in a function involves some heap allocation. Code could we look like this. I didn't include any checks if there is a real float returned or not. This is your task

    #include <stdio.h>
    #include <stdlib.h>
    
    
    void* square (const void* num);
    
    int main() {
      float *x, sq_int;
      float value = 6;
      x = square(&value);
      printf("%f squared is %f\n", value, *x);
      free(x);
      return 0;
    }
    
    void* square (const void *num) {
      float *result = malloc(sizeof(float));
      *result = (*(float *)num) * (*(float *)num);
      return ((float*)result);
    }