In C, a void* is an implication convertible to T* , where T is any type. From section 6.3.2.3 Pointers to C99:
A pointer to void can be converted to a pointer to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type can be converted to a pointer to void and vice versa; The result is compared with the original pointer.
malloc() returns void* and is assigned without quotation marks to head , a struct node* . This is not the case in C ++, so I suspect that the C ++ compiler is used to compile this C code.
For instance:
#include <stdlib.h> int main() { int* i = malloc(sizeof(*i)); return 0; }
when compiling with:
gcc -Wall -Werror -pedantic -std = c99 -pthread main.c -o main
no mistakes. When compiled with:
g ++ -Wall -Werror -pedantic -std = C ++ 11 -pthread main.cpp -o main
emits:
main.cpp: In the function 'int main ()': main.cpp: 5:31: error: incorrect conversion from 'void *' to 'int *' [-fpermissive]
In addition, the onetwothree() function does not allocate memory correctly. It allocates only one struct node :
head = malloc(sizeof(struct node));
and then, ultimately, playing head->next->next , which are undefined. Each struct node requires an individual malloc() . Remember free() , which was malloc() d.
source share