The following code when compiled gives the error: "invalid conversion from `void*' to `f*' "
What is wrong with it ?

typedef struct a
    int* value;
    struct a* p;
    int r;

f* m(int* value)
    f* node = malloc(sizeof(f));
    node->value = value;
    node->p = NULL;
    node->r = 0;
    return node;
8 Years
Discussion Span
Last Post by akssps011

No, this is a snipped from the code. I have mentioned here the structure definition(which is obviously global) and the function in which it is used.
The function is used in the main function.
The error occurs at line 10


Appears as if you are compiling it as C++ code instead of C.

PS. When you post code snippets, try including everything relevant to the given piece of code/errors. I.e. in this case, you most likely are including <stdlib.h>, but that does not show in the snippet (even little things can make a whole lot of difference in terms of the compiler output).

In case of C++ compiler, you need to typecast the pointer returned by malloc() , in C, you don't have to do that.

Edited by mitrmkar: n/a

Votes + Comments

so that means that in C++ t should be something like this
f* node = f(malloc(sizeof(f)));

Edited by akssps011: n/a


Actually in C++ you would want to be avoiding malloc() in the first place and using new instead. So ..

// No need to cast anything
 f * node = new f;

If you (for some reason) use malloc() , you can still use C-style casts to some extent, (i.e. in this case (f*) ) or a C++ cast. But perhaps remember, that casts are best avoided.

Edited by mitrmkar: 'to some extent'

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.