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 have 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With