When I compile this part of code in my computer I get this error:(I use DEV C++) >>>> ERROR: invalid conversion from´void*' to ´node*'

but when I compiled it in my friend compiler(DEV C++) , it works seamlessly.

I WANT TO KNOW WHAT MY COMPILER PROBLEM IS?

Reedbeta
—
2009-06-14T20:58:52Z —
#2

First, please use ...[/code] when posting code. Second, please indicate what line of the program is giving the error. I'm going to guess that it is the line calling malloc(). The solution is to use a type cast: nptr = (node *)malloc(sizeof(struct node)). This instructs the compiler to treat the output of malloc as a node * even though it's really a void *. The reason the compiler doesn't do this automatically is because technically it is not type-safe. A void * can point to any data at all, which may or may not be a 'node' struct, so it is not safe to treat it as a node *. Whatever compiler your friend is using may let you get away with this specifically for malloc() as a special case, for convenience, but you shouldn't rely on this behavior. (Note: DevC++ is the IDE, not the compiler.) [code]...[/code****] when posting code.

Second, please indicate what line of the program is giving the error. I'm going to guess that it is the line calling malloc().

The solution is to use a type cast: nptr = (node *)malloc(sizeof(struct node)). This instructs the compiler to treat the output of malloc as a node * even though it's really a void *.

The reason the compiler doesn't do this automatically is because technically it is not type-safe. A void * can point to any data at all, which may or may not be a 'node' struct, so it is not safe to treat it as a node *.

Whatever compiler your friend is using may let you get away with this specifically for malloc() as a special case, for convenience, but you shouldn't rely on this behavior. (Note: DevC++ is the IDE, not the compiler.)

kotiloli
—
2009-06-15T08:22:06Z —
#3

thans for your guide.

Trap_D
—
2009-06-15T09:41:32Z —
#4

If you use a C compiler (you have a file xxx.c) you have no error, but with a C++ compiler (you have a file xxx.cpp) you have an error.

oisyn
—
2009-06-15T15:08:04Z —
#5

Yup, this is typical C code (with the 'struct node variable' definitions and malloc()). C allows implicit casts from void* to T*, but C++ doesn't. You obviously try to compile the code with the compiler in C++ mode, while your friend is compiling it in C mode.

monjardin
—
2009-06-16T02:12:09Z —
#6

These cast would be a pain in C since void* is the only way to approach the flexibility of templates.