Invalid conversion from 'void *' to 'node *' [-fpermissive]

I have a C program that creates an error:

invalid conversion from 'void*' to 'node*' [-fpermissive] 

Here is my code:

 #include<stdio.h> #include<conio.h> #include<stdlib.h> struct node { int data; struct node* next; }; struct node* onetwothree(); int main() { struct node* ptr; ptr = onetwothree(); return 0; } struct node* onetwothree() { struct node* head; struct node* temp; head = malloc(sizeof(struct node)); temp = head; for(int i=1; i<=3; i++) { temp->data = i; if(i<3) temp=temp->next; else temp->next = NULL; } return head; } 

What am I doing wrong?

+6
source share
2 answers

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.

+15
source

You have this warning / error because you are using malloc (which returns void* ) to initialize a structure of type node* without making an explicit cast.

To get rid of this error, you can change your code as follows:

 head = (struct node *)malloc(sizeof(struct node)); 

or you can also add the -fpermissive flag to your compiler, which will then ignore these errors.

EDIT: But yes, I did not think that this should not happen in the C compiler anyway

+2
source

Source: https://habr.com/ru/post/946016/


All Articles