C++:malloc:错误:从“void*”到“uint8_t*”的无效转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4010917/
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
C++: malloc : error: invalid conversion from ‘void*’ to ‘uint8_t*’
提问by olidev
I got this problem:
我遇到了这个问题:
invalid conversion from ‘void*' to ‘uint8_t*'
从“void*”到“uint8_t*”的无效转换
When doing this:
这样做时:
int numBytes;
uint8_t *buffer;
buffer=malloc(numBytes); //error here, why?
or must I have to put it like this?
还是我必须这样说?
buffer=malloc(numBytes);
Please explain this.
请解释一下。
回答by Oliver Charlesworth
You cannot implicitly cast from void *
in C++ (unlike C in this respect). You could do:
您不能void *
在 C++ 中隐式转换(在这方面与 C 不同)。你可以这样做:
buffer = static_cast<uint8_t *>(malloc(numBytes));
but really, you should just be using new
/delete
instead of malloc
/free
!
但实际上,您应该只使用new
/delete
而不是malloc
/ free
!
回答by Sam Dufel
Malloc returns a void pointer; when you use it, you have to cast the return value to a pointer to whatever datatype you're storing in it.
Malloc 返回一个空指针;当您使用它时,您必须将返回值转换为指向您存储在其中的任何数据类型的指针。
buffer = (uint8_t *) malloc(numBytes);
回答by Nils Pipenbrinck
In C++ it is not allowed to simply assign a pointer of one type to a pointer of another type (as always there are exception to the rule. It is for example valid to assign a any pointer to a void pointer.)
在 C++ 中,不允许简单地将一种类型的指针分配给另一种类型的指针(因为规则总是有例外。例如,将 any 指针分配给 void 指针是有效的。)
What you should do is to cast your void pointer to a uint8_t pointer:
您应该做的是将 void 指针转换为 uint8_t 指针:
buffer = (uint8_t *) malloc (numBytes);
Note: This is only necessary in C++, in C it was allowed to mix and match pointers. Most C compilers give a warning, but it is valid code.
注意:这仅在 C++ 中是必需的,在 C 中允许混合和匹配指针。大多数 C 编译器都会发出警告,但它是有效的代码。
Since you're using C++ you could also use new and delete like this:
由于您使用的是 C++,您还可以像这样使用 new 和 delete:
buffer = new uint8_t[numBytes];
and get rid of your buffer using:
并使用以下方法摆脱缓冲区:
delete[] buffer;
In general you shouldn't use malloc and free unless you have to interface with c libraries.
一般来说,除非必须与 c 库接口,否则不应使用 malloc 和 free。