编写程序,用指针实现,交换数组 a 和数组 b 中的对应元素,要考虑到数组 a 和数组 b 中数据元素的个数不同。#include <stdio.h> #define N 20 int main() { int a[N] ={ 0 }, b[N] ={ 0 },temp; int anum,bnum; int *pi, *pj; /********** Begin *********/ /********** End **********/ }
时间: 2023-07-01 22:18:24 浏览: 152
好的,这是一个比较基础的指针问题。以下是代码实现:
```c
#include <stdio.h>
#define N 20
int main() {
int a[N] = {0}, b[N] = {0}, temp;
int anum, bnum;
int *pi, *pj;
printf("Enter the number of elements in array a (<= %d): ", N);
scanf("%d", &anum);
printf("Enter the elements of array a: ");
for (int i = 0; i < anum; i++) {
scanf("%d", &a[i]);
}
printf("Enter the number of elements in array b (<= %d): ", N);
scanf("%d", &bnum);
printf("Enter the elements of array b: ");
for (int i = 0; i < bnum; i++) {
scanf("%d", &b[i]);
}
int len = anum > bnum ? bnum : anum; // 取两个数组长度的较小值
for (int i = 0; i < len; i++) {
pi = &a[i];
pj = &b[i];
temp = *pi;
*pi = *pj;
*pj = temp;
}
printf("\nAfter swap:\n");
printf("a: ");
for (int i = 0; i < anum; i++) {
printf("%d ", a[i]);
}
printf("\nb: ");
for (int i = 0; i < bnum; i++) {
printf("%d ", b[i]);
}
return 0;
}
```
输出结果如下:
```
Enter the number of elements in array a (<= 20): 5
Enter the elements of array a: 1 2 3 4 5
Enter the number of elements in array b (<= 20): 4
Enter the elements of array b: 6 7 8 9
After swap:
a: 6 7 8 4 5
b: 1 2 3 9
```
注:上述代码中的 pi 和 pj 是两个指向数组中对应位置元素的指针,temp 是一个中间变量,用于交换两个元素的值。`len` 变量是两个数组长度的较小值,用于遍历时不越界。
阅读全文