0

I'm having trouble converting an int into a float. I tried to type convert but it doesn't seem to work. What am I doing wrong?

float *six(const int *x) {
    float *p = malloc(sizeof(x));
    p = (float *)x;
    return p;
}

int main() {
    float *p_six;
    int i4 = 4, i432 = 432;

    p_six = six(&i4);
    printf("%d == %f\n", i4, *p_six);
    free(p_six);
}
1
  • The p = (float *)x; assignment in the function obliterates the pointer to the memory allocated in the previous line, so you have a memory leak every time you call the function. Commented Apr 8, 2017 at 20:52

1 Answer 1

3

You can't point a float * to an int and expect it to be interpreted properly. They have very different representations, so you'll end up with garbage.

All you need to do is assign your int value to a float and it will be converted.

int main()
{
    float f;
    int i = 4;

    f = i;
    printf("%d == %f\n", i, f);
    return 0;
}

Output:

4 == 4.000000
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.