Swap Array Elements in C Language

In C language, you can swap array elements by defining a swap function. Here is a specific implementation:

#include <stdio.h>

void swap(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int nums[] = {1, 2, 3, 4, 5};
    int size = sizeof(nums) / sizeof(nums[0]);

    // 交换数组中的第一个和最后一个元素
    swap(&nums[0], &nums[size - 1]);

    // 输出交换后的数组
    for (int i = 0; i < size; i++) {
        printf("%d ", nums[i]);
    }

    return 0;
}

In the above code, the swap function swaps the values of two elements by passing in two pointers to array elements as parameters. In the main function, we define an integer array nums and calculate the size of the array using the sizeof operator. We then call the swap function to swap the first and last elements in the array. Finally, we iterate through the array using a for loop and use the printf function to output the swapped array elements.

bannerAds