I have an incr
function to increment the value by 1
I want to make it generic,because I don't want to make different functions for the same functionality.
Suppose I want to increment int
,float
,char
by 1
void incr(void *vp)
{
(*vp)++;
}
But the problem I know is Dereferencing a void pointer is undefined behaviour
. Sometimes It may give error :Invalid use of void expression
.
My main
funciton is :
int main()
{
int i=5;
float f=5.6f;
char c='a';
incr(&i);
incr(&f);
incr(&c);
return 0;
}
The problem is how to solve this ? Is there a way to solve it in C
only
or
will I have to define incr()
for each datatypes ? if yes, then what's the use of void *
Same problem with the swap()
and sort()
.I want to swap and sort all kinds of data types with same function.
You can't do exactly what you're asking - operators like increment need to work with a specific type. So, you could do something like this:
Then you'd call it like:
Of course, this doesn't really give you anything over just defining separate
incr_int()
,incr_float()
andincr_char()
functions - this isn't the purpose ofvoid *
.The purpose of
void *
is realised when the algorithm you're writing doesn't care about the real type of the objects. A good example is the standard sorting functionqsort()
, which is declared as:This can be used to sort arrays of any type of object - the caller just needs to supply a comparison function that can compare two objects.
Both your
swap()
andsort()
functions fall into this category.swap()
is even easier - the algorithm doesn't need to know anything other than the size of the objects to swap them:Now given any array you can swap two items in that array:
You should cast your pointer to concrete type before dereferencing it. So you should also add code to pass what is the type of pointer variable.
Using
void *
will not give you polymorphic behavior, which is what I think you're looking for.void *
simply allows you to bypass the type-checking of heap variables. To achieve actual polymorphic behavior, you will have to pass in the type information as another variable and check for it in yourincr
function, then casting the pointer to the desired type OR by passing in any operations on your data as function pointers (others have mentionedqsort
as an example). C does not have automatic polymorphism built in to the language, so it would be on you to simulate it. Behind the scenes, languages that build in polymorphism are doing something just like this behind the scenes.To elaborate,
void *
is a pointer to a generic block of memory, which could be anything: an int, float, string, etc. The length of the block of memory isn't even stored in the pointer, let alone the type of the data. Remember that internally, all data are bits and bytes, and types are really just markers for how the logical data are physically encoded, because intrinsically, bits and bytes are typeless. In C, this information is not stored with variables, so you have to provide it to the compiler yourself, so that it knows whether to apply operations to treat the bit sequences as 2's complement integers, IEEE 754 double-precision floating point, ASCII character data, functions, etc.; these are all specific standards of formats and operations for different types of data. When you cast avoid *
to a pointer to a specific type, you as the programmer are asserting that the data pointed to actually is of the type you're casting it to. Otherwise, you're probably in for weird behavior.So what is
void *
good for? It's good for dealing with blocks of data without regards to type. This is necessary for things like memory allocation, copying, file operations, and passing pointers-to-functions. In almost all cases though, a C programmer abstracts from this low-level representation as much as possible by structuring their data with types, which have built-in operations; or using structs, with operations on these structs defined by the programmer as functions.You may want to check out the Wikipedia explanation for more info.
Sorry if this may come off as a non-answer to the broad question "How to make generic function using void * in c?".. but the problems you seem to have (incrementing a variable of an arbitrary type, and swapping 2 variables of unknown types) can be much easier done with macros than functions and pointers to void.
Incrementing's simple enough:
For swapping, I'd do something like this:
...which works for ints, doubles and char pointers (strings), based on my testing.
Whilst the incrementing macro should be pretty safe, the swap macro relies on the
typeof()
operator, which is a GCC/clang extension, NOT part of standard C (tho if you only really ever compile with gcc or clang, this shouldn't be too much of a problem).I know that kind of dodged the original question; but hopefully it still solves your original problems.
You can implement the first as a macro:
Of course, this can have unpleasant side effects if you're not careful. It's about the only method C provides for applying the same operation to any of a variety of types though. In particular, since the macro is implemented using text substitution, by the time the compiler sees it, you just have the literal code
++whatever;
, and it can apply++
properly for the type of item you've provided. With a pointer to void, you don't know much (if anything) about the actual type, so you can't do much direct manipulation on that data).void *
is normally used when the function in question doesn't really need to know the exact type of the data involved. In some cases (e.g.,qsort
) it uses a callback function to avoid having to know any details of the data.Since it does both sort and swap, let's look at qsort in a little more detail. Its signature is:
So, the first is the
void *
you asked about -- a pointer to the data to be sorted. The second tells qsort the number of elements in the array. The third, the size of each element in the array. The last is a pointer to a function that can compare individual items, soqsort
doesn't need to know how to do that. For example, somewhere inside qsort will be some code something like:Likewise, to swap two items, it'll normally have a local array for temporary storage. It'll then copy bytes from
array[i]
to its temp, then fromarray[j]
toarray[i]
and finally fromtemp
toarray[j]
:Example for using "Generic" swap.
This code swaps two blocks of memory.
And you call it like this:
I think that this should give you an idea of how to use one function for different data types.