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;

f* m(int* value)
{
    f* node = malloc(sizeof(f));
    node->value = value;
    node->p = NULL;
    node->r = 0;
    return node;
}

Recommended Answers

All 9 Replies

Is this the complete program?

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

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

commented: Nice +19

oh yes, I was mistakenly compiling it as cpp. How did you figured it out >

I've seen it before :)

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

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;

[EDIT]
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.

thankyou..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.