题目
将数组A中的内容和数组B中的内容进行交换。(数组一样大)
解题方式通过函数封装可以实现任意类型的数组元素交换
思路来源:qsort函数的模拟实现
void Change_arr2(void* ch1, void* ch2, size_t num, size_t sz)
{for (int i = 0; i < num * sz; i++){char tmp = *(char*)ch1;*(char*)ch1 = *(char*)ch2;*(char*)ch2 = tmp;((char*)ch1)++;((char*)ch2)++;}
}
void test1()
{char ch1[] = "abcdefg";char ch2[] = "hijklmn";int num = sizeof(ch1) / sizeof(ch1[0]);int sz = sizeof(ch1[0]);//Change_arr1(ch1, ch2, num, sz);Change_arr2(&ch1, &ch2, num, sz);printf("%s\n", ch1);printf("%s\n", ch2);
}
void test2()
{int ch1[] = { 1,2,3,4,5 };int ch2[] = { 6,7,8,9,10 };int num = sizeof(ch1) / sizeof(ch1[0]);int sz = sizeof(ch1[0]);//Change_arr1(ch1, ch2, num, sz);Change_arr2(&ch1, &ch2, num, sz);for (int i = 0; i < num; i++){printf("%d ", ch1[i]);}printf("\n");for (int i = 0; i < num; i++){printf("%d ", ch2[i]);}
}
typedef struct std
{char name[20];int age;
}std;
void test3()
{std ch1[] = { {.name="张三",.age=20},{.name = "王五",.age = 24} };std ch2[] = { {.name = "李四",.age = 18} ,{.name = "赵六",.age = 16} };int num = sizeof(ch1) / sizeof(ch1[0]);int sz = sizeof(ch1[0]);//Change_arr1(ch1, ch2, num, sz);Change_arr2(&ch1, &ch2, num, sz);for (int i = 0; i < num; i++){printf("%d %s ", ch1[i].age,ch1[i].name);}printf("\n");for (int i = 0; i < num; i++){printf("%d %s ", ch2[i].age, ch2[i].name);}
}
int main()
{//test1();//交换字符数组//test2();//交换整型数组test3();//交换结构体return 0;
}