0
101 Jun 14, 2009 at 20:16
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *nextNode;
};
int main(){
struct node node1,*nptr;
node1.data=10;
node1.nextNode=NULL;
nptr=&node1;
nptr= malloc(sizeof(struct node));
nptr->data=100;
nptr->nextNode=&node1;

return 0;
}


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?

#### 5 Replies

0
165 Jun 14, 2009 at 20:58

First, please use …[/code[b][/b]] 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.)

0
101 Jun 15, 2009 at 08:22

0
101 Jun 15, 2009 at 09:41

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.

0
101 Jun 15, 2009 at 15:08

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.

0
102 Jun 16, 2009 at 02:12

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