c语言中检测两段数组相关性的函数
时间: 2023-10-28 22:17:09 浏览: 92
在C语言中,可以使用以下函数来检测两段数组的相关性:
1. memcmp函数
memcmp函数可以比较两个内存区域的内容是否相等,如果相等返回0,不相等则返回非0值。因此,可以利用该函数来检测两段数组的相关性。
示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
int arr1[] = {1, 2, 3, 4};
int arr2[] = {1, 2, 3, 4};
int arr3[] = {1, 2, 3, 5};
int res1 = memcmp(arr1, arr2, sizeof(arr1));
int res2 = memcmp(arr1, arr3, sizeof(arr1));
if (res1 == 0) {
printf("arr1 and arr2 are identical.\n");
} else {
printf("arr1 and arr2 are not identical.\n");
}
if (res2 == 0) {
printf("arr1 and arr3 are identical.\n");
} else {
printf("arr1 and arr3 are not identical.\n");
}
return 0;
}
```
输出结果:
```
arr1 and arr2 are identical.
arr1 and arr3 are not identical.
```
2. strcmp函数
strcmp函数用于比较两个字符串(包括字符数组)是否相等,如果相等返回0,不相等则返回非0值。因此,可以利用该函数来检测两段字符数组的相关性。
示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "hello";
char str3[] = "world";
int res1 = strcmp(str1, str2);
int res2 = strcmp(str1, str3);
if (res1 == 0) {
printf("str1 and str2 are identical.\n");
} else {
printf("str1 and str2 are not identical.\n");
}
if (res2 == 0) {
printf("str1 and str3 are identical.\n");
} else {
printf("str1 and str3 are not identical.\n");
}
return 0;
}
```
输出结果:
```
str1 and str2 are identical.
str1 and str3 are not identical.
```
阅读全文