Invalid conversion from 'void * to' unsigned char *

I have the following code:

void* buffer = operator new(100); unsigned char* etherhead = buffer; 

When I try to compile, I get the following error for this line:

 error: invalid conversion from 'void*' to 'unsigned char*' 

Why am I getting this error, I thought the void was β€œwithout a clutch,” so it can point to anything, or can something point to it?

+6
source share
6 answers

You need to enable it, because you cannot convert the void * into anything without pronouncing it first.

You will need to do

 unsigned char* etherhead = (unsigned char*)buffer; 

(although you can also use static_cast )

To learn more about void pointers, see 6.13 - Void Pointers .

+9
source

A void* can point to anything, and you can convert the pointer to something else in void* without translation, but you must use static_cast to reverse the conversion.

 unsigned char* etherhead = static_cast<unsigned char*>(buffer); 

If you need a dynamically allocated buffer of 100 unsigned char , you better do this and avoid casting.

 unsigned char* p = new unsigned char[100]; 
+5
source

You can convert any pointer to void *, but you cannot convert void * to anything else without translation. This may help suggest that "void" is the base class for EVERYTHING, and "int" and "char" and not all subclasses of "void" yet.

+4
source

Here's a bit of lateral thinking: whenever you think you need throws or pointers, think again. If you need only 100 unsigned bytes of memory, use

 std::array<unsigned char, 100> data; 

or

 unsigned char data[100]; 

If the size is not constant, use a vector:

 std::vector<unsigned char> data(size); 

Raw pointers, the new operator, and throws are unsafe, hard to access, and make your program difficult to understand. Avoid them if possible.

+3
source

C ++ is designed to be more type safe than C. If it is C code, this may be good, but it also depends on which compiler you are using right now.

Also, technically, "extern" C "int *" and "int *" are different types ... (for example, the Solaris compiler will choose this)

I suggest you use C ++ listing instead of C cast. Here are more descriptions:

Normal listing versus static_cast vs. dynamic_cast .

+1
source
 void *pt; pt=(void*)&i; pt=(void*)&dbl; 

Here is how I would do it.

0
source

Source: https://habr.com/ru/post/913216/


All Articles