下面是使用指针解决的代码示例:
- #include
-
- void swap(int *a, int *b) {
- int temp = *a;
- *a = *b;
- *b = temp;
- }
-
- int main() {
- int arr[100], n, max_index = 0, min_index = 0;
- printf("Enter the size of the array: ");
- scanf("%d", &n);
- printf("Enter the elements of the array: ");
- for (int i = 0; i < n; i++) {
- scanf("%d", &arr[i]);
- if (arr[i] > arr[max_index]) {
- max_index = i;
- }
- if (arr[i] < arr[min_index]) {
- min_index = i;
- }
- }
-
- swap(&arr[max_index], &arr[0]); // 交换最大值和第一个元素
- swap(&arr[min_index], &arr[n - 1]); // 交换最小值和最后一个元素
-
- printf("The modified array is: ");
- for (int i = 0; i < n; i++) {
- printf("%d ", arr[i]);
- }
- printf("\n");
-
- return 0;
- }
使用指针可以避免大量的数组拷贝操作,提高程序的效率。在程序中,我们使用 swap() 函数交换数组中的两个元素,其中,函数的参数都是指针类型,即指向变量的地址。使用该函数,代码变得更加简洁易懂。
