Official Solution
#include <stdio.h>
#include <string.h>
/* Generic swap function */
void swap(void *a, void *b, size_t size) {
char temp[size]; // temporary buffer
memcpy(temp, a, size); // store a in temp
memcpy(a, b, size); // copy b to a
memcpy(b, temp, size); // copy temp to b
}
int main() {
int x = 10, y = 20;
float f1 = 1.5f, f2 = 2.5f;
char str1[] = "Hello", str2[] = "World";
/* Swap integers */
swap(&x, &y, sizeof(int));
printf("Swapped integers: x=%d, y=%dn", x, y);
/* Swap floats */
swap(&f1, &f2, sizeof(float));
printf("Swapped floats: f1=%.2f, f2=%.2fn", f1, f2);
/* Swap strings (arrays of char) */
swap(str1, str2, sizeof(str1)); // use sizeof(str1) for fixed-size array
printf("Swapped strings: str1=%s, str2=%sn", str1, str2);
return 0;
}
No comments yet. Start the discussion!