开发者

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

开发者 https://www.devze.com 2023-01-22 06:39 出处:网络
I got this problem: invalid conversion from ‘void*’ to ‘uint8_t*’ When doing this: intnumBytes; uint8_t*buffer;

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

精彩评论

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