I have a C program that produces an error:
invalid conversion from \'void*\' to \'node*\' [-fpermissive]
Here\'s my code:
In C, a void* is implicity convertible to a T* where T is any type. From section 6.3.2.3 Pointers of the C99 standard:
A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
malloc() returns a void* and is assignable without casting to head, a struct node*. This is not true in C++, so I suspect a C++ compiler is being used to compile this C code.
For example:
#include <stdlib.h>
int main()
{
int* i = malloc(sizeof(*i));
return 0;
}
when compiled with:
gcc -Wall -Werror -pedantic -std=c99 -pthread main.c -o main
emits no errors. When compiled with:
g++ -Wall -Werror -pedantic -std=c++11 -pthread main.cpp -o main
emits:
main.cpp: In function 'int main()': main.cpp:5:31: error: invalid conversion from 'void*' to 'int*' [-fpermissive]
Additionally, the onetwothree() function is not allocating memory correctly. It allocates one struct node only:
head = malloc(sizeof(struct node));
and then, eventually, dereferences head->next->next which is undefined behaviour. An individual malloc() is required for every struct node.
Remember to free() what was malloc()d.
You're having this warning/error because you are using malloc (which returns a void*)to initialize a structure of type node* without doing an explicit cast.
To get rid of this error you could change your code this way :
head = (struct node *)malloc(sizeof(struct node));
or you could as well add the "-fpermissive" flag to your compiler which will then ignore these errors.
EDIT: But yeah, i didn't think about the fact that this should not happen in a C compiler anyways
Use:
head = (struct node*) malloc(sizeof(struct node));
C++ does not support implicit conversion of void* returned by malloc(), which C does. You'll need to typecast the return value.