#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*
* generic_swap
* ------------
* Swaps the contents of two variables of arbitrary type.
*
* Parameters:
* a, b - pointers to the two objects to swap
* size - size (in bytes) of the objects being swapped
*
* This function uses a temporary buffer and memcpy to perform the swap.
*/
void generic_swap(void *a, void *b, size_t size) {
void *temp = malloc(size);
if (!temp) {
fprintf(stderr, "Memory allocation failed\n");
exit(1);
}
memcpy(temp, a, size);
memcpy(a, b, size);
memcpy(b, temp, size);
free(temp);
}
/*
* Print arrays of integers
*/
void print_int_array(int *arr, int n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
printf("=== TEST 1: Swap integers ===\n");
int x = 10, y = 20;
printf("Before: x=%d, y=%d\n", x, y);
generic_swap(&x, &y, sizeof(int));
printf("After: x=%d, y=%d\n\n", x, y);
printf("=== TEST 2: Swap doubles ===\n");
double a = 3.14, b = 2.71;
printf("Before: a=%.2f, b=%.2f\n", a, b);
generic_swap(&a, &b, sizeof(double));
printf("After: a=%.2f, b=%.2f\n\n", a, b);
printf("=== TEST 3: Swap structs ===\n");
struct Point { int x, y; };
struct Point p1 = {1, 2}, p2 = {9, 8};
printf("Before: p1=(%d,%d), p2=(%d,%d)\n", p1.x, p1.y, p2.x, p2.y);
generic_swap(&p1, &p2, sizeof(struct Point));
printf("After: p1=(%d,%d), p2=(%d,%d)\n\n", p1.x, p1.y, p2.x, p2.y);
printf("=== TEST 4: Swap array elements ===\n");
int arr[] = {1, 2, 3, 4, 5};
printf("Before: ");
print_int_array(arr, 5);
generic_swap(&arr[1], &arr[3], sizeof(int));
printf("After: ");
print_int_array(arr, 5);
printf("\n");
printf("=== TEST 5: Swap strings ===\n");
char str1[20] = "Hello";
char str2[20] = "World";
printf("Before: str1=\"%s\", str2=\"%s\"\n", str1, str2);
generic_swap(str1, str2, sizeof(str1));
printf("After: str1=\"%s\", str2=\"%s\"\n\n", str1, str2);
return 0;
}
/*
run:
=== TEST 1: Swap integers ===
Before: x=10, y=20
After: x=20, y=10
=== TEST 2: Swap doubles ===
Before: a=3.14, b=2.71
After: a=2.71, b=3.14
=== TEST 3: Swap structs ===
Before: p1=(1,2), p2=(9,8)
After: p1=(9,8), p2=(1,2)
=== TEST 4: Swap array elements ===
Before: 1 2 3 4 5
After: 1 4 3 2 5
=== TEST 5: Swap strings ===
Before: str1="Hello", str2="World"
After: str1="World", str2="Hello"
*/