Invalid conversion from ‘void*’ to ‘unsigned char*’

时间秒杀一切 提交于 2019-12-04 06:50:18

You need to cast as you can not convert a void* to anything without casting it first.

You would need to do

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

(although you could use a static_cast also)

To learn more about void pointers, take a look at 6.13 — Void pointers.

A void* might point at anything and you can convert a pointer to anything else to a void* without a cast but you have to use a static_cast to do the reverse.

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

If you want a dynamically allocated buffer of 100 unsigned char you are better off doing this and avoiding the cast.

unsigned char* p = new unsigned char[100];

You can convert any pointer to a void *, but you can't convert void * to anything else without a cast. It might help to imagine that "void" is the base class for EVERYTHING, and "int" and "char" and whatnot are all subclasses of "void."

Here's a bit of lateral thinking: Whenever you think you need casts or pointers, think again. If all you need is 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 casts are unsafe, hard to get right and make your program harder to understand. Avoid them if possible.

Spike

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

Also, technically, "extern "C" int *" and "int *" are different types... (like solaris compiler will pick this out)

I would suggest you using C++ style cast instead of C cast. There are more descriptions here:

Regular cast vs. static_cast vs. dynamic_cast.

void *pt; 

pt=(void*)&i; 
pt=(void*)&dbl; 

Here's how I would do it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!