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

前端 未结 3 672
说谎
说谎 2020-12-11 04:24

I have a C program that produces an error:

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

Here\'s my code:

         


        
相关标签:
3条回答
  • 2020-12-11 04:35

    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.

    0 讨论(0)
  • 2020-12-11 04:58

    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

    0 讨论(0)
  • 2020-12-11 04:59

    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.

    0 讨论(0)
提交回复
热议问题