Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One swap function to be used by 2 different structs

Tags:

c

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.

like image 476
Ultimate Tc Avatar asked Sep 28 '22 06:09

Ultimate Tc


1 Answers

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));
like image 89
Ja͢ck Avatar answered Oct 19 '22 22:10

Ja͢ck