One swap function to be used by two different structures

I wonder if it is possible for one function, such as swap (), to be used in two different structures to replace them? 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 this, is it possible for the swap function to change elements in the structures? For example, you can use: 1. swap (arr [1], arr [2]); 2. swap (brr [1], brr [2]);

From my point of view, such a thing cannot be done, since the data type for the struct (and also its element) is different. I was interested in creating a modular function for one of my projects, so the help would be really appreciated.

Thanks.

+5
source share
2 answers

You will need a generic function that replaces memory addresses 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 elements, you pass their addresses:

 swap(&arr[1], &arr[2], sizeof(one)); 
+4
source

This is a macro, not a function. I tested it on GCC and Clang on Linux x86-64 with -O1 optimization. It seems that the compilers are smart enough to get rid of malloc, memcpy and free for small structures. This code should compile with something less than a proper function call.

 #define swap(a, i1, i2)\ {\ size_t size = sizeof(a[i1]);\ void *tmp_elm = malloc(size);\ memcpy(tmp_elm, &a[i1], size);\ memcpy(&a[i1], &a[i2], size);\ memcpy(&a[i2], tmp_elm, size);\ free(tmp_elm);\ } 

Usage example:

 one arr[8]; two brr[8]; /* Set these two arrays. */ swap(arr, 1, 2); swap(brr, 1, 2); 
0
source

All Articles