在 C 中,唯一可以应用于结构变量的操作是赋值。不允许对结构变量进行任何其他操作(例如相等检查)。
例如,程序 1 运行时没有任何错误,而程序 2 编译失败。
程序 1
程序 2
#include <stdio.h>
struct Point {
int x;
int y;
};
int main()
{
struct Point p1 = {10, 20};
struct Point p2 = p1; // works: contents of p1 are copied to p2
printf(" p2.x = %d, p2.y = %d", p2.x, p2.y);
getchar();
return 0;
}
#include <stdio.h>
struct Point {
int x;
int y;
};
int main()
{
struct Point p1 = {10, 20};
struct Point p2 = p1; // works: contents of p1 are copied to p2
if (p1 == p2) // compiler error: cannot do equality check for
// whole structures
{
printf("p1 and p2 are same ");
}
getchar();
return 0;
}