c - 比较两个 union 时“二进制操作数的无效操作数”

标签 c compiler-errors linked-list binary-operators

我正在编写一段代码,用于在 C 中实现与类型无关的链表。这就是我正在努力做的事情。

  1. 创建一个可以存储以下任意一个的 union :int、char*、double、char。

    union 元素 { int num;字符* 字符串;双实数;炭阿尔夫; };

  2. 用于跟踪 union 存储的元素的枚举。

    枚举 { NUM, STR, REAL, CHAR };

  3. 将存储节点值的结构。

    结构节点 { int 类型; union 元素数据;结构节点*下一个; };

  4. 由于我可能有多个列表,因此我还为节点创建一个容器,

    struct list { 结构节点 *head; };

现在我想创建一个函数来从列表中获取元素。其功能是,

node* findkey(list *l, union element key)
{
    node *i=list->head;
    while(!i) {
        if(i->data == key) {
            return i;
        i=i->next;
    }
    return NULL;
}

当我编译代码时,clang 向我抛出此错误,

linkedlist.c:33:11: error: invalid operands to binary expression ('union element' and
      'union element')
                if(i->data == key)
                   ~~~~ ^  ~~~
1 error generated.

最佳答案

这里

if(i->data == key) {

它的比较 union 变量是无效的,如 Harbison and Steele book 中所述。

Structures and unions cannot be compared for equality, even though assignment for these types is allowed. The gaps in structures and unions caused by alignment restrictions could contain arbitrary values, and compensating for this would impose an unacceptable overhead on the equality comparison or on all operations that modified structure and union types.

您可以比较 union 成员,例如

if(i->data.num == key.num) {
 /*  some code */    
}

关于c - 比较两个 union 时“二进制操作数的无效操作数”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52251137/

相关文章:

python - 出现 Python 异常时 PyObject_CallObject 的正确返回是什么?

java - Java GUI程序不会生成随机形状吗?

java - 在链表类中实现 Iterator 接口(interface)

C++ 错误 : no match for call to ‘(std::string {aka std::basic_string<char>}) (std::string&)’

c - 如何修复 linux 内核部分不匹配?

java - 子列表实现

java - 使用Java在Hadoop中形成自定义链接列表

c - 使用 wget 编程并将文件保存到内存中

c - 为什么 memccpy 函数使用 int 参数?

c - 删除空格后的垃圾输出