【发布时间】:2011-06-26 18:40:38
【问题描述】:
为什么整个结构不能在 C 中比较,但可以复制? 换句话说,为什么下面程序中的比较不起作用?它不打印字符串。
#include <stdio.h>
#include <string.h>
int main(void)
{
struct emp
{
char n[20];
int age;
};
struct emp e1={"David",23};
struct emp e2=e1;
if(e2 == e1)
{
printf("The structures are equal");
}
return(0);
}
【问题讨论】:
-
因为运算符
==不知道它需要比较的结构的所有成员,所以你知道! -
"它不打印字符串。"但它甚至不编译。 “错误:二进制 == 的操作数无效(有‘struct emp’和‘struct emp’)”
-
你也不能在 C 中比较字符串 - 至少不能用 '==' 或等价物。
(struct emp){"David", 30}和(struct emp){"Alfred", 20}的顺序是什么,为什么?如果结构包含指向其他结构而不是简单字符串的指针怎么办?等等。 -
if (0 == memcmp(&e1, &e2, sizeof(struct emp))) { /* Structures are equal */ }
标签: c