开发者

What is the meaning of this?

开发者 https://www.devze.com 2023-02-16 21:00 出处:网络
Code: void *buff; char *r_b开发者_Python百科uff = (char *)buff; I can\'t understand the type casting of buff. Please help.

Code:

void *buff; 
char *r_b开发者_Python百科uff = (char *)buff;

I can't understand the type casting of buff. Please help.

Thank you.


buff is a pointer to some memory, where the type of its content is unspecified (hence the void).

The second line tells that r_buff shall point to the same memory location, and the contents shall be interpreted as char(s).


buff is typed as a void pointer, which means it points to memory without declaring anything about the contents.

When you cast to char *, you declare that you're interpreting the pointer as being a char pointer.


In well written C++, you should not use C-style casts. So your cast should look like this:

void *buff; 
char *r_buff = static_cast<char *>(buff);

See here for an explanation of what the C++ casting operators do.


By its name, buff is likely to be a memory buffer in which to write data, possibly binary data.

There are reasons why one might want to cast it to char *, potentially to use pointer arithmetic on it as one is writing because you cannot do that with a void*.

For example if you are supplied also a size (likely) and your API requires not pointer and size but 2 pointers (begin and end) you will need pointer arithmetic to determine where the end is.

The code could well be C in which case the cast is correct. If the code is C++ though a static_cast is preferable although the C cast is not incorrect in this instance. The reason a static_cast is generally preferred is that the compiler will catch more occasions when you cast incorrectly that way, and it is also more easily greppable. However casting in general breaks type-safety rules and therefore is preferably avoided much of the time. (Not that it is never correct, as it may be here).

0

精彩评论

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

关注公众号