C++ 使用 malloc 时从“void*”到“char*”的无效转换?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5099669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
invalid conversion from `void*' to `char*' when using malloc?
提问by pandoragami
I'm having trouble with the code below with the error on line 5:
我在使用下面的代码时遇到了问题,第 5 行出现错误:
error: invalid conversion from
void*
tochar*
错误:从
void*
到的无效转换char*
I'm using g++ with codeblocks and I tried to compile this file as a cpp file. Does it matter?
我将 g++ 与代码块一起使用,并尝试将此文件编译为 cpp 文件。有关系吗?
#include <openssl/crypto.h>
int main()
{
char *foo = malloc(1);
if (!foo) {
printf("malloc()");
exit(1);
}
OPENSSL_cleanse(foo, 1);
printf("cleaned one byte\n");
OPENSSL_cleanse(foo, 0);
printf("cleaned zero bytes\n");
}
回答by karlphillip
In C++, you need to cast the return of malloc()
在 C++ 中,您需要强制转换为 malloc()
char *foo = (char*)malloc(1);
回答by Marlon
C++ is designed to be more type safe than C, therefore you cannot (automatically) convert fromvoid*
toanother 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*
.
C ++的设计是比C类型安全的,所以你不能(自动)转换从void*
到另一个指针类型。由于您的文件是 a .cpp
,您的编译器需要 C++ 代码,并且如前所述,您对 malloc 的调用将无法编译,因为您将 a 分配给了char*
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.
如果您将文件更改为 a.c
那么它将需要 C 代码。在 C 中,您不需要指定void*
与其他指针类型之间的强制转换。如果您将文件更改为 a .c
,它将成功编译。
回答by viraptor
I assume this is the line with malloc. Just cast the result then - char *foo = (char*)...
我认为这是 malloc 的行。只需投射结果然后 -char *foo = (char*)...
回答by AnT
So, what was your intent? Are you trying to write a C program or C++ program?
那么,你的意图是什么?您是在尝试编写 C 程序还是 C++ 程序?
If you need a C program, then don't compile it as C++, i.e. either don't give your file ".cpp" extension or explicitly ask the compiler to treat your file as C. In C language you should not cast the result of malloc
. I assume that this is what you need since you tagged your question as [C].
如果您需要 C 程序,则不要将其编译为 C++,即不要给您的文件“.cpp”扩展名或明确要求编译器将您的文件视为 C。在 C 语言中,您不应该转换结果的malloc
。我认为这是您需要的,因为您将问题标记为 [C]。
If you need a C++ program that uses malloc
, then you have no choice but to explicitly cast the return value of malloc
to the proper type.
如果您需要一个使用 的 C++ 程序malloc
,那么您别无选择,只能将 的返回值显式malloc
转换为正确的类型。