If you always define the data
first in each struct, and data
is always an int, then you can do something like this:
void swapData(void* elem1, void* elem2) //<- the problem is here
{
int* e1 = (int*) elem1;
int* e2 = (int*) elem2;
int temp = e1[0];
e1[0] = e2[0];
e2[0] = temp;
}
the reason this works is because when you pass a void *, you get memory of size sizeof(One)
or whatever you put in. since the data
is first, we can just pretend that you passed in an array of integers, and take the first one. If you had a more complicated structure, you could build a struct where the first few elements are the same types as any struct you might pass in. this way you could manipulate multiple objects. that would look something like this:
typedef struct {
int data;
char * name;
...
} complicated;
typedef struct {
int data;
char * name;
int something_else;
} simple;
typedef struct { // least common denominator
int data;
char * name;
} common;
void swap(void * e1, void* e2){
common* c1 = (common*) e1;
common* c2 = (common*) e2;
int tmp = c1->data;
char * tmpn = c1->name;
c1->data = c2->data;
c1->name = c2->name;
c2->data = tmp;
c2->name = tmp;
}
hope this makes sense.