C語言中的結構體變數操作


這裡我們將瞭解哪些型別的操作可以針對結構體變數執行。這裡,基本上可以對結構體執行一項操作。該操作是賦值操作。棧中沒有其他一些操作,如相等性檢查或其他操作。

示例

#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)

由於我們已經為結構體賦予了一些值,因此這工作得很好。現在,如果我們想要比較兩個結構體物件,讓我們看看區別。

示例

#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("Complex numbers are same.");
   } else {
      printf("Complex numbers are not same.");
   }
}

輸出

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

更新時間:2019 年 7 月 30 日

1K+ 瀏覽

開啟你的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.