โครงสร้าง คือชุดของตัวแปรประเภทข้อมูลต่างๆ รวมกันเป็นชื่อเดียว
คุณสมบัติของโครงสร้าง
คุณสมบัติของโครงสร้างในภาษาซีมีดังนี้ −
-
เป็นไปได้ที่จะคัดลอกเนื้อหาขององค์ประกอบโครงสร้างทั้งหมดของประเภทข้อมูลที่แตกต่างกันไปยังตัวแปรโครงสร้างอื่นของประเภทโดยใช้ตัวดำเนินการกำหนด
-
สำหรับการจัดการประเภทข้อมูลที่ซับซ้อน จะเป็นการดีกว่าที่จะสร้างโครงสร้างภายในโครงสร้างอื่นซึ่งเรียกว่าโครงสร้างที่ซ้อนกัน
-
เป็นไปได้ที่จะส่งผ่านโครงสร้างทั้งหมด องค์ประกอบแต่ละส่วนของโครงสร้าง และที่อยู่ของโครงสร้างไปยังฟังก์ชัน
-
สามารถสร้างตัวชี้โครงสร้างได้
โปรแกรม
ต่อไปนี้เป็นโปรแกรม C จัดเก็บระบบสินค้าคงคลังโดยใช้โครงสร้าง −
#include<stdio.h>
#include<conio.h>
void main(){
struct date{
int day;
int month;
int year;
};
struct details{
char name[20];
int price;
int code;
int qty;
struct date mfg;
};
struct details item[50];
int n,i;
printf("Enter number of items:");
scanf("%d",&n);
fflush(stdin);
for(i=0;i<n;i++){
fflush(stdin);
printf("Item name:");
scanf("%s",item[i].name);
fflush(stdin);
printf("Item code:");
scanf("%d",&item[i].code);
fflush(stdin);
printf("Quantity:");
scanf("%d",&item[i].qty);
fflush(stdin);
printf("price:");
scanf("%d",&item[i].price);
fflush(stdin);
printf("Manufacturing date(dd-mm-yyyy):");
scanf("%d-%d-%d",&item[i].mfg.day,&item[i].mfg.month,&item[i].mfg.year);
}
printf(" ***** INVENTORY *****\n");
printf("------------------------------------------------------------------\n");
printf("S.N.| NAME | CODE | QUANTITY | PRICE |MFG.DATE\n");
printf("------------------------------------------------------------------\n");
for(i=0;i<n;i++)
printf("%d %-15s %-d %-5d %-5d%d/%d/%d\n",i+1,item[i].name,item[i].code,item[i].qty,item[i].price,item[i].mfg.day,item[i].mfg.month,item[i].mfg.year);
printf("------------------------------------------------------------------\n");
getch();
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
Enter number of items:5 Item name:pen Item code:12 Quantity:50 price:25 Manufacturing date(dd-mm-yyyy):12-02-2020 Item name:pencil Item code:15 Quantity:100 price:30 Manufacturing date(dd-mm-yyyy):11-03-2020 Item name:book Item code:34 Quantity:30 price:60 Manufacturing date(dd-mm-yyyy):15-04-2020 Item name:bag Item code:39 Quantity:20 price:70 Manufacturing date(dd-mm-yyyy):12-03-2021 Item name:sharpner Item code:33 Quantity:20 price:40 Manufacturing date(dd-mm-yyyy):12-04-2021 ***** INVENTORY ***** ------------------------------------------------------------------ S.N.| NAME | CODE | QUANTITY | PRICE |MFG.DATE ------------------------------------------------------------------ 1 pen 12 50 25 12/2/2020 2 pencil 15 100 30 11/3/2020 3 book 34 30 60 15/4/2020 4 bag 39 20 70 12/3/2021 5 sharpner 33 20 40 12/4/2021