[英]Invalid operands comparing a struct to null
I'm trying to debug the following error I have in my code:我正在尝试调试代码中的以下错误:
#define MAX_PATTERNS 10
typedef struct _kv {
char* key;
char* val;
} KV;
void compile(char* pattern)
{
KV patterns[MAX_PATTERNS] = {NULL,};
for (int idx=0; idx < MAX_PATTERNS; idx++) {
KV item = patterns[idx];
printf("%d", item == 0);
}
}
And I get the following error:我收到以下错误:
test.c:107:27: error: invalid operands to binary expression ('KV' (aka 'struct _kv') and 'int')
printf("%d", item == 0);
~~~~ ^ ~
error generated.
What am I doing wrong here?我在这里做错了什么? I thought that I could use a
patterns[idx] == NULL
to test when I can exit the loop (since I'm initializing the array to all zero's), but I seem to be wrong on something.我认为我可以使用
patterns[idx] == NULL
来测试我何时可以退出循环(因为我将数组初始化为全零),但我似乎在某些方面是错误的。 Should I instead check patterns[idx].key
to see if that's NULL
?我应该检查
patterns[idx].key
以查看是否是NULL
吗?
I suppose one (ugly) way to check if the entire struct is zero'd is by doing:我想检查整个结构是否为零的一种(丑陋)方法是:
printf ("Null? %s\n",
(int) (void*) patterns[0].key + (int) (void*) patterns[0].val == 0? "true" : "false");
Well, the error message says it all... you are trying to compare a struct _kv
and an int
.好吧,错误消息说明了一切……您正在尝试比较
struct _kv
和int
。 It makes no sense to compare objects of completely different types to each other so that's illegal.将完全不同类型的对象相互比较是没有意义的,因此这是非法的。
But even worse... C doesn't allow you to compare structs using ==
Not even if the structs are of the same type.但更糟糕的是...... C 不允许您使用
==
比较结构,即使结构属于同一类型。 Example:例子:
KV item1 = patterns[idx1];
KV item2 = patterns[idx2];
if (item1 == item2) puts("e");
will give an error like:将给出如下错误:
error: invalid operands to binary == (have ‘KV’ {aka ‘struct _kv’} and ‘KV’ {aka ‘struct _kv’})
To compare structs you need to compare the members one by one.要比较结构,您需要一一比较成员。
You ask if it's done like:你问它是否像这样完成:
(int) (void*) patterns[0].key + (int) (void*) patterns[0].val == 0
The answer is NO答案是否定的
Instead do而是做
patterns[0].key == NULL && patterns[0].val == NULL
If your program compares structs several places in the code, it may be a good idea to write a dedicated compare function - like:如果您的程序比较代码中的多个位置的结构,最好编写一个专门的比较 function - 例如:
int equal_kv(const KV* a, const KV* b)
{
return a->key == b->key && a->val == b->val;
}
and use it like:并像这样使用它:
KV item1 = patterns[idx1];
KV item2 = patterns[idx2];
if equal_kv(&item1, &item2) puts("e");
In my humble point of view, I totally agree with kaylum's point.以我谦虚的观点,我完全同意凯勒姆的观点。 "item" 's data type is a struct and cannot be compared directly with a integer type variable or literal integer.
"item" 的数据类型是结构,不能直接与 integer 类型变量或字面量 integer 进行比较。 Instead, in C++, we can use operator overloading to redefine the "==" operator for custom data types such as any custom class or struct.
相反,在 C++ 中,我们可以使用运算符重载来为自定义数据类型(例如任何自定义 class 或结构)重新定义“==”运算符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.