[英]How can I compare two 2D arrays in C?
我试试看,但这段代码运行不稳定。
我有两个二维 arrays first[a][b]
和second[x][y]
。
我想比较这两个 arrays。 我怎样才能做到这一点?
我的代码:
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
if (first[i][j] == second[i][j])
return 1;
另一种方法是使用memcmp
。
注意:这适用于现代架构,其中int
没有任何填充位。 感谢@chqrlieforyellowblockquotes 指出这一点。
#include <stdio.h>
#include <string.h>
int main() {
int a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int b[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int c[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 123}};
int ret;
ret = memcmp(a, b, 3 * 3 * sizeof(int));
if (ret == 0)
printf("a equal b\n");
else
printf("a not equal b\n");
ret = memcmp(a, c, 3 * 3 * sizeof(int));
if (ret == 0)
printf("a equal c\n");
else
printf("a not equal c\n");
return 0;
}
Output
a equal b
a not equal c
通过您的代码,我看到:
如果 arrays 中的相应元素之一相等,则 arrays 都相等。
但我认为你想要这个:
如果 arrays 中的所有相应元素都相等,则 arrays 都相等
这不会在您的代码中发生,因为当相应元素之一相等( ==
)时,您会立即return
ing,因此您的代码会省略剩余的检查。
解决方案:
if( first[i][j]==second[i][j])
更改为if (first[i][j] != second[i][j])
这将寻找第一个不相等的元素。 然后,您可以return
适当的消息或break
,具体取决于您对该代码的具体操作。
您在正确的轨道上,但如果所有条目都相同,则 arrays 是相同的。 发现差异时应返回 0,否则应返回 1:
int compare_matrices(int first[10][10], int second[10][10]) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (first[i][j] != second[i][j])
return 0;
}
}
return 1;
}
没有填充位的常规架构的替代方案是使用memcmp()
:
#include <string.h>
int compare_matrices(int first[10][10], int second[10][10]) {
return !memcmp(first, second, 10 * sizeof(*first));
}
第一个代码很简单,但编译器可以通过展开循环来优化它,并且可以产生与memcmp()
相当或更好的性能。
减少测试次数会增加 memory 访问次数,但可能会产生更好的性能,因为编译器可以使用 SIMD 指令:
int compare_matrices(int first[10][10], int second[10][10]) {
for (int i = 0; i < 10; i++) {
int res = 0;
for (int j = 0; j < 10; j++) {
res |= (first[i][j] != second[i][j]);
}
if (res) return 0;
}
return 1;
}
您可以使用GodBolt 的 Compiler Explorer来比较代码生成器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.