I wonder if it is possible for 1 function such as swap() to be used in two different structs to swap them? So for example,
typedef struct{
char a;
}one;
typedef struct{
int c;
}two;
swap(??,??){
// code to swap 2 elements
}
one arr[8];
arr[1].a='a';
arr[2].a='b';
two brr[8];
brr[1].c = 11;
brr[2].c = 12;
So, based on that, is it possible for swap function to be able to swap the elements in structs? E.g is it possible to use: 1. swap(arr[1],arr[2]); 2. swap(brr[1],brr[2]);
From my understanding, such thing cannot be done since the data type for both struct (and also its element) are different. I've been wondering of making a modular function for one my project so help would be really appreciated.
Thanks.
You would need a generic function that takes memory addresses to swap instead:
void swap(void *a, void *b, size_t size)
{
void *tmp = malloc(size);
// you should make sure the memory allocation was successful
memcpy(tmp, a, size);
memcpy(a, b, size);
memcpy(b, tmp, size);
free(tmp);
}
Instead of the elements, you pass in their addresses:
swap(&arr[1], &arr[2], sizeof(one));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With