我尝试了一下,但是这段代码运行不稳定。
有两个二维数组first[a][b]
和second[x][y]
。
我想比较这两个数组。我怎样才能做到这一点?
我的代码:
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;
}
输出
a equal b
a not equal c
关于c - 如何在 C 中比较两个二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61120864/