1、解决方案
设计一个循环,对两个数组同时依次遍历,每变一次都执行交换操作,这样遍历结束就完成了数组的交换。
2、具体的交换方法的实现
void exchangeArray(int max, int* a, int* b)//exchange the two same size arrays, num is the size
{
//交换的实现
int temp = 0;
for(int i = 0; i < max; i++)
{
temp = *(a + i);
*(a + i) = *(b+i);
*(b + i) = temp;
}
//展示交换后的结果
printf("交换后数组a:");
for(int i = 0; i < max; i++)
{
printf("%d\t", *(a + i));
}
printf("\n");
printf("交换后数组b:");
for(int i = 0; i < max; i++)
{
printf("%d\t", *(b + i));
}
printf("\n");
}
3、测试
void exchangeArray(int max, int* a, int* b)//exchange the two same size arrays, num is the size
{
int temp;
for(int i = 0; i < max; i++)
{
temp = *(a + i);
*(a + i) = *(b+i);
*(b + i) = temp;
}
//展示交换后的结果
printf("交换后数组a:");
for(int i = 0; i < max; i++)
{
printf("%d\t", *(a + i));
}
printf("\n");
printf("交换后数组b:");
for(int i = 0; i < max; i++)
{
printf("%d\t", *(b + i));
}
printf("\n");
}
int main()
{
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int b[10] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
printf("交换前数组a:");
for(int i = 0; i < 10; i++)
{
printf("%d\t", *(a + i));
}
printf("\n");
printf("交换前数组b:");
for(int i = 0; i < 10; i++)
{
printf("%d\t", *(b + i));
}
printf("\n\n");
exchangeArray(10, a, b);
printf("\n");
system("pause");
return 0;
}
结果为: