开发者

C++: malloc : error: invalid conversion from ‘void*’ to ‘uint8_t*’

I got this problem:

invalid conversion from ‘void*’ to ‘uint8_t*’

When doing this:

int             numBytes;
uint8_t         *buffer;

buffer=malloc(numBytes); //error here, why?

or must I h开发者_JS百科ave to put it like this?

buffer=malloc(numBytes); 

Please explain this.


You cannot implicitly cast from void * in C++ (unlike C in this respect). You could do:

buffer = static_cast<uint8_t *>(malloc(numBytes));

but really, you should just be using new/delete instead of malloc/free!


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.)

What you should do is to cast your void pointer to a uint8_t pointer:

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.

Since you're using C++ you could also use new and delete like this:

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.


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.

buffer = (uint8_t *) malloc(numBytes); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜