比较两个数据结构的值

标签 c data-structures comparison

我有两个数据结构:

typedef struct{
    int a;
    int b;
    int c;
}EVENTS;

EVENTS typeone[20];
EVENTS typetwo[20];

这些已经被填满了。 typeone 被填充到 typeone[5],typetwo 被填充到 typetwo[8]。

我只是想比较一下typeone和typetwo的前六个,看看他们的所有成员是否相等。

有没有办法做到typeone[1] == typetwo[1] 基本上比较 [1] 处数据结构内的所有值。 有没有一种简短的方法可以做到这一点,还是我必须遍历每个成员并分别进行比较?

谢谢

最佳答案

这是一个 comp.lang.c FAQ .简而言之,不,C 不支持使用 == 运算符进行结构比较(常见问题解答中的答案说明了为什么这在一般情况下很难)。您必须编写自己的函数并逐个比较成员。正如所指出的那样,memcmp()不是有保证的方法,因为访问填充字节时未指定的行为

int eventsequal (const EVENTS *const a, const EVENTS *const b)
{
    if (a->a != b->a) return 0;
    if (a->b != b->b) return 0;
    if (a->c != b->c) return 0;
    return 1;
}

然后您的示例 typeone[1] == typetwo[1] 变为

if (eventsequal (typeone + 1, typetwo + 1)) {
   /* They're equal. */
}

关于比较两个数据结构的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13932856/

相关文章:

c - 读取 float 的最小缓冲区长度

c - fork() pipeline() dup2 无法与外部子进程通信

c - 如何在 c 中获取 .exe 文件属性详细信息?

Java : BST - removing a node with no children doesn't work

java - 比较法违反了它的一般契约。简单比较

c - C 中的 string_comparator

java - 最大堆未按预期工作

algorithm - 范围树 : why not save space by default?

ruby-on-rails - Ruby Enumerable 无法在 min 函数中比较 BigDecimal NaN

javascript - 使用自纪元以来的毫秒数比较 JavaScript 中的日期和时间