Computer >> Máy Tính >  >> Lập trình >> C ++

Các thao tác trên biến cấu trúc trong C

Ở đây chúng ta sẽ xem loại hoạt động nào có thể được thực hiện trên các biến struct. Về cơ bản, một thao tác có thể được thực hiện đối với struct. Hoạt động là hoạt động phân công. Một số thao tác khác như kiểm tra bình đẳng hoặc các thao tác khác không khả dụng cho ngăn xếp.

Ví dụ

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

Đầu ra

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

Điều này hoạt động tốt vì chúng tôi đã gán một số giá trị vào struct. Bây giờ, nếu chúng ta muốn so sánh hai đối tượng struct, hãy xem sự khác biệt.

Ví dụ

#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.");
   }
}

Đầu ra

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