Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C เปรียบเทียบตัวแปรโครงสร้าง (Structure Variables)

การเปรียบเทียบโครงสร้าง (Struct) ในภาษา C

C ไม่รองรับการเปรียบเทียบ struct ด้วย == โดยตรง ต้องเปรียบเทียบสมาชิกทีละตัว หรือใช้ memcmp (ต้องระวัง padding)

การประกาศและกำหนดค่า Struct

struct book {
    int pages;
    char author[30];
    float price;
};

// วิธี 1: ประกาศพร้อมตัวแปร
struct book { ... } b;

// วิธี 2: ไม่มี tag name
struct { ... } b;

// วิธี 3: แยกประกาศ tag และตัวแปร
struct book { ... };
struct book b;

การกำหนดค่าเริ่มต้น

// วิธี 1
struct book b = {100, "balu", 325.75};

// วิธี 2
struct book b = {100, "balu", 325.75};

// วิธี 3: ใช้ dot operator
struct book b;
b.pages = 100;
strcpy(b.author, "balu");
b.price = 325.75;

ตัวอย่างเปรียบเทียบ 2 โครงสร้าง

struct class {
    int number;
    char name[20];
    float marks;
};

main() {
    int x;
    struct class student1 = {001, "Hari", 172.50};
    struct class student2 = {002, "Bobby", 167.00};
    struct class student3;
    student3 = student2; // copy ทั้ง struct
    x = ((student3.number == student2.number) && (student3.marks == student2.marks)) ? 1 : 0;
    if (x == 1) {
        printf("\nstudent2 and student3 are same\n\n");
        printf("%d %s %f\n", student3.number, student3.name, student3.marks);
    } else
        printf("\nstudent2 and student3 are different\n\n");
}

Output: student2 and student3 are same 2 Bobby 167.000000

หมายเหตุ: ตัวอย่างเปรียบเทียบเฉพาะ number และ marks ไม่รวม name หากต้องการเปรียบเทียบ string ใช้ strcmp