## 用C语言编写交换数组数值的代码教程

4用C语言编写交换数组数值的代码教程

#include

void swap(int *a, int *b) {

int temp = *a;

*a = *b;

*b = temp;

}

int main() {

int arr[] = {4, 2, 6, 1, 8};

int size = sizeof(arr) / sizeof(arr[0]);

int firstIndex = 0;

int secondIndex = 3;

printf(\交换前的数组：\ for (int i = 0; i < size; i++) {

printf(\d \ arr[i]);

}

printf(\n\ swap(&arr[firstIndex], &arr[secondIndex]);

printf(\交换后的数组：\ for (int i = 0; i < size; i++) {

printf(\d \ arr[i]);

}

printf(\n\ return 0;

}

#include

void swap(void *a, void *b, size_t size) {

char temp[size];

memcpy(temp, a, size);

memcpy(a, b, size);

memcpy(b, temp, size);

}

int main() {

int arr1[] = {4, 2, 6, 1, 8};

int size1 = sizeof(arr1) / sizeof(arr1[0]);

int firstIndex1 = 0;

int secondIndex1 = 3;

double arr2[] = {3.14, 2.71, 1.41, 2.23};

int size2 = sizeof(arr2) / sizeof(arr2[0]);

int firstIndex2 = 1;

int secondIndex2 = 2;

printf(\交换前的整型数组：\ for (int i = 0; i < size1; i++) {

printf(\d \ arr1[i]);

}

printf(\n\ swap(&arr1[firstIndex1], &arr1[secondIndex1], sizeof(int));

printf(\交换后的整型数组：\ for (int i = 0; i < size1; i++) {

printf(\d \ arr1[i]);

}

printf(\n\ printf(\交换前的双精度浮点型数组：\ for (int i = 0; i < size2; i++) {

printf(\2lf \ arr2[i]);

}

printf(\n\ swap(&arr2[firstIndex2], &arr2[secondIndex2], sizeof(double));

printf(\交换后的双精度浮点型数组：\ for (int i = 0; i < size2; i++) {

printf(\2lf \ arr2[i]);

}

printf(\n\ return 0;

}