I wanted to implement a swap function that works with all data types. I now know that this is not easily possible without malloc etc. But my real confusion is about why the following functions work with different data types:
//short int unsigned long
void swapInt(char* a, char* b)
{
char tmp = *a;
*a = *b;
*b = tmp;
}
//double long
void swapDouble(void **pptr1, void **pptr2)
{
void *temp1 = *pptr1;
*pptr1 = *pptr2;
*pptr2 = temp1;
}
//float
void swapFloat(void *a, void *b){
int aux;
aux = *(int*)(a);//
*(int*)(a) = *(int*)(b);
*(int*)(b) = aux;
}
int main()
{
#define SIZE 5
int array[SIZE]={1,2,2,2,5};
printf("before:\n ");
for(int i=0; i < SIZE; i++)
printf("%d ", array[i]);
swapInt(&array[0], &array[4]);
printf("\n");
printf("after:\n ");
for(int i=0; i < SIZE; i++)
printf("%d ", array[i]);
return 0;
}
The output of the main as it is shown in the code block was:
before:
1 2 2 2 5
after:
5 2 2 2 1
If I change the array to double or float its:
before:
1.000000 2.000000 2.000000 2.000000 5.000000
after:
1.000000 2.000000 2.000000 2.000000 5.000000
Testing it with the other functions, it still gives different results for different data types. Please explain this to me, it's really frustrating.
EDIT:
I used this online compiler https://www.onlinegdb.com/online_c_compiler
the warnings I get are following:
main.c:37:12: warning: passing argument 1 of ‘swapInt’ from incompatible pointer type [-Wincompatible-pointer-types]
main.c:4:6: note: expected ‘char *’ but argument is of type ‘int *’
main.c:37:23: warning: passing argument 2 of ‘swapInt’ from incompatible pointer type [-Wincompatible-pointer-types]
main.c:4:6: note: expected ‘char *’ but argument is of type ‘int *’
And it works, or I wouldn't have said it works. I tried different functions I found on stack overflow and now I'm confused why they work or seem to work.
char *arguments for int,void **for double, andvoid *for float? First step is to fix those to bevoid swapInt(int *a, int *b)and similar. The way it is now, it doesn't work even for ints, try for example to set the first element ofarrayto-1instead of1.void swapInt(int *a, int *b).