invalid conversion from `void*' to `char*' when using malloc?

后端 未结 4 1818
野趣味
野趣味 2020-11-27 15:26

I\'m having trouble with the code below with the error on line 5:

error: invalid conversion from void* to char*

4条回答
  •  北海茫月
    2020-11-27 16:01

    C++ is designed to be more type safe than C, therefore you cannot (automatically) convert from void* to another pointer type. Since your file is a .cpp, your compiler is expecting C++ code and, as previously mentioned, your call to malloc will not compile since your are assigning a char* to a void*.

    If you change your file to a .c then it will expect C code. In C, you do not need to specify a cast between void* and another pointer type. If you change your file to a .c it will compile successfully.

提交回复
热议问题