1、逐个元素比较法
遍历两个数组的每个元素,并逐个比较它们的值。
#include <stdio.h> #include <stdbool.h> bool arraysEqual(int arr1[], int arr2[], int size) { for (int i = 0; i < size; ++i) { if (arr1[i] != arr2[i]) { return false; } } return true; } int main() { int arr1[] = {1, 2, 3, 4, 5}; int arr2[] = {1, 2, 3, 4, 5}; int size = sizeof(arr1) / sizeof(arr1[0]); if (arraysEqual(arr1, arr2, size)) { printf("Arrays are equal.\n"); } else { printf("Arrays are not equal.\n"); } return 0; }
2、memcmp函数比较法
使用memcmp
函数直接比较两个数组的内容是否相等。
#include <stdio.h> #include <string.h> int main() { int arr1[] = {1, 2, 3, 4, 5}; int arr2[] = {1, 2, 3, 4, 5}; int size = sizeof(arr1); if (memcmp(arr1, arr2, size) == 0) { printf("Arrays are equal.\n"); } else { printf("Arrays are not equal.\n"); } return 0; }
3、数组指针比较法
比较两个数组的指针是否相同。
#include <stdio.h> int main() { int arr1[] = {1, 2, 3, 4, 5}; int arr2[] = {1, 2, 3, 4, 5}; if (arr1 == arr2) { printf("Arrays are equal.\n"); } else { printf("Arrays are not equal.\n"); } return 0; }
4、使用memcmp和sizeof结合法
结合使用memcmp
和sizeof
来确保比较整个数组的内容。
#include <stdio.h> #include <string.h> int main() { int arr1[] = {1, 2, 3, 4, 5}; int arr2[] = {1, 2, 3, 4, 5}; if (memcmp(arr1, arr2, sizeof(arr1)) == 0) { printf("Arrays are equal.\n"); } else { printf("Arrays are not equal.\n"); } return 0; }
5、使用循环和标志位法
使用循环遍历数组并使用标志位进行比较。
#include <stdio.h> #include <stdbool.h> bool arraysEqual(int arr1[], int arr2[], int size) { bool equal = true; for (int i = 0; i < size; ++i) { if (arr1[i] != arr2[i]) { equal = false; break; } } return equal; } int main() { int arr1[] = {1, 2, 3, 4, 5}; int arr2[] = {1, 2, 3, 4, 5}; int size = sizeof(arr1) / sizeof(arr1[0]); if (arraysEqual(arr1, arr2, size)) { printf("Arrays are equal.\n"); } else { printf("Arrays are not equal.\n"); } return 0; }