Try said:
Hello !
I was wondering how to create a function that can be applied to all
type of variables?
Not exactly sure what you want here. Do you want to pass just a pointer of
any type to your function? If so, void * coupled with another formal
parameter that tells you the type is one easy approach. There are no
"magic" solutions here. You have to slog it out and write the code for
both passing the type as well as the data and handling both inside your
function. For instance:
int sortList(int type, void *obj) {
switch ( type ) {
case 1:
{ /* obj has type pointer-to-int */
int *data = obj;
...
}
break;
case 2:
{
/* obj has type pointer-to-float */
float *data = obj;
...
}
break;
...
}
}
void doStuff() {
int *intlist;
...
sortList(1, intlist);
}
You get the idea. If you're tempted to do this however, I would like you to
consider writing separate functions to handle each type rather than this
approach.
If all you're looking for is general purpose sorting of data, consider using
the library's qsort function. All you need to provide is the comparison
function for the data you want to sort. For instance, to sort an array of
integers:
#include <stdio.h>
int cmpints(const void *in1, const void *in2) {
const int *i1 = in1;
const int *i2 = in2;
if ( *i1 < *i2 )
return -1;
if ( *i1 > *i2 )
return 1;
return 0;
}
void sortList(size_t sz, int *list) {
qsort(list, sz, sizeof *list, cmpints);
}
If you need to pass an arbitrary number of parameters of arbitrary types, a
format string based varargs function along the lines of the *printf/*scanf
family can be used.
If we use for example, sortList(void *obj), we can not do the
comparison of 2 strcut.
strcut? Did you mean strcmp? You can write a wrapper function that calls
strcmp, and then use it along with qsort.
-nrk.