สร้าง Struct ในภาษา C สำหรับจัดกลุ่มตัวแปร

Programming 05 กุมภาพันธ์ พ.ศ. 2566 297
Home / Articles / 36

ในบทความนี้จะเป็นการแนะนำการจัดกลุ่มตัวแปรโดยใช้ Struct ซึ่งทำให้เราสามารถเรียกใช้ตัวแปรต่างๆที่อยู่ใน Struct ได้ ทำให้เราสามารถจัดกลุ่มของตัวแปรต่างๆ ไว้เป็นกลุ่มๆ ได้ ตัวอย่างเช่น หากมีตัวแปร name อยู่ใน struct ที่ชื่อว่า peoples เวลาเรียกก็จะเรียกโดยใช้ peoples.name หรือหากเป็น Array จะเรียกโดยใส่จำนวนแถวเข้าไปด้วย เช่น peoples[0].name

ตัวอย่างโจทย์การเก็บรายการสินค้า

หากผมต้องการเก็บ รายการสินค้า จำนวนไม่เกิน 20 แถว โดยมีตัวแปร id, name, price ซึ่งมีชื่อโครงสร้าง struct ว่า "products" ต้องเขียนโครงสร้างดังนี้ โดยมี pointer เท่ากับ products (ใช้สำหรับอ้างอิงไปหา struct)

struct products{
    int id;
    char name[20];
    float price;
} products[20];

ผมสามาถกำหนดค่าให้กับ Struct แถวที่ 0 ได้ โดยเรียกใช้ตัวแปรดังนี้

products[0].id = 1;
products[0].name = "Cold-Beer";
products[0].price = 50;

เช่นเดียวกับ ตัวแปรชนิดปกติ ข้อมูล Cold-Beer ก็จะถูกใส่เข้าไปในแถวที่ศูนย์ เราสามารถประยุกต์ใช้กับ For Loop เพื่อรับค่า และแสดงผลได้ ดังตัวอย่างนี้

#include <stdio.h>

main() {
    struct products{
        int id;
        char name[20];
        float price;
    } products[20];

    for(int i = 0; i < 3; i++) {
        printf("Enter ID: ");
        scanf("%d", products[i].id);
        printf("Enter Name: ");
        scanf("%s", products[i].name);
        fflush(stdin); 
        printf("Enter Price: ");
        scanf("%f", products[i].price);
    }
    printf("===================== \n");
    for(int i = 0; i < 3; i++) {
        printf("ID: %d \n",products[i].id);
        printf("Name: %s \n",products[i].name);
        printf("Price: %.2f \n",products[i].price);
    }
}

จากโปรแกรมเป็นการ Loops รับค่าและแสดงผลเพียง 3 ครั้ง ผลลัพท์จะได้ดังนี้

Enter ID: 1
Enter Name: Cold-Beer
Enter Price: 55
Enter ID: 2
Enter Name: Cigar 
Enter Price: 120
Enter ID: 3
Enter Name: Water
Enter Price: 20
===================== 
ID: 1 
Name: Cold-Beer 
Price: 55.00 
ID: 2 
Name: Cigar 
Price: 120.00
ID: 3 
Name: Water 
Price: 20.00 

การใช้ Struct สามารถนำไปปรับใช้กับการเก็บข้อมูลคล้ายกับ ฐานข้อมูล ได้ โดยเราจะสามารถเก็บข้อมูลไว้ใน Text File หรือ Binary File ได้ ซึ่งผมจะพาไปแนะนำในบทความต่อไป

Profile Picture.
  • Name (Pen name): Sunny Jirakit (Sunny420x)
  • Study: Bachelor Degree of Computer Science from Chiang Mai Rajabhat University
  • Personality: Architect (INTJ-T)
  • Experience: JavaScript,  Angular.js, React.js, Next.js  Express.js, Unity C#, Socket.io