Chicko Bueno
Chicko Bueno

Reputation: 337

What is the meaning of this?

Code:

void *buff; 
char *r_buff = (char *)buff;

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

Thank you.

Upvotes: 2

Views: 4071

Answers (4)

CashCow
CashCow

Reputation: 31445

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).

Upvotes: 1

Björn Pollex
Björn Pollex

Reputation: 76876

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.

Upvotes: 4

Zr40
Zr40

Reputation: 1919

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.

Upvotes: 6

phimuemue
phimuemue

Reputation: 36071

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).

Upvotes: 10

Related Questions