Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

void* or char* for generic buffer representation?

Tags:

c++

arrays

buffer

I'm designing a Buffer class whose purpose is to represent a chunk of memory.

My underlying buffer is a char* (well, a boost::shared_array<char> actually, but it doesn't really matter).

I'm stuck at deciding what prototype to choose for my constructor:

Should I go with:

Buffer(const void* buf, size_t buflen);

Or with:

Buffer(const char* buf, size_t buflen);

Or something else ?

What is usually done, and why ?

like image 483
ereOn Avatar asked Sep 28 '10 13:09

ereOn


People also ask

When would you use a void pointer?

Why do we use a void pointer in C programs? We use the void pointers to overcome the issue of assigning separate values to different data types in a program. The pointer to void can be used in generic functions in C because it is capable of pointing to any data type.

What is void * in C?

The void pointer in C is a pointer which is not associated with any data types. It points to some data location in the storage means points to the address of variables. It is also called general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.

What does char buffer do in C?

Returns a string containing the characters in this buffer. Wraps a character sequence into a buffer.

Can we assign a void pointer to an int type pointer?

Now, we want to assign the void pointer to integer pointer, in order to do this, we need to apply the cast operator, i.e., (int *) to the void pointer variable. This cast operator tells the compiler which type of value void pointer is holding.


2 Answers

API interface is more clear for user, if buffer has void* type, and string has char* type. Compare memcpy and strcpy function definitions.

like image 158
Alex F Avatar answered Oct 08 '22 13:10

Alex F


For the constructor and other API functions, the advantage of void* is that it allows the caller to pass in a pointer to any type without having to do an unnecessary cast. If it makes sense for the caller to be able to pass in any type, then void* is preferable. If it really only makes sense for the caller to be able to pass in char*, then use that type.

like image 20
Mike Morearty Avatar answered Oct 08 '22 13:10

Mike Morearty