在C中对结构变量进行运算

在这里,我们将看到可以对结构变量执行哪种类型的操作。这里基本上可以对struct执行一个操作。该操作是分配操作。其他一些操作(如相等性检查或其他操作)不可用于堆栈。

示例

#include <stdio.h>
typedef struct { //define a structure for complex objects
   int real, imag;
}complex;
void displayComplex(complex c){
   printf("(%d + %di)\n", c.real, c.imag);
}
main() {
   complex c1 = {5, 2};
   complex c2 = {8, 6};
   printf("Complex numbers are:\n");
   displayComplex(c1);
   displayComplex(c2);
}

输出结果

Complex numbers are:
(5 + 2i)
(8 + 6i)

由于我们已将一些值分配给struct,因此效果很好。现在,如果我们要比较两个结构对象,让我们看一下区别。

示例

#include <stdio.h>
typedef struct { //define a structure for complex objects
   int real, imag;
}complex;
void displayComplex(complex c){
   printf("(%d + %di)\n", c.real, c.imag);
}
main() {
   complex c1 = {5, 2};
   complex c2 = c1;
   printf("Complex numbers are:\n");
   displayComplex(c1);
   displayComplex(c2);
   if(c1 == c2){
      printf("复数相同。");
   } else {
      printf("复数不一样。");
   }
}

输出结果

[Error] invalid operands to binary == (have 'complex' and 'complex')