โครงสร้างคือชุดของตัวแปรประเภทข้อมูลต่างๆ ที่จัดกลุ่มเข้าด้วยกันภายใต้ชื่อเดียว
คุณสมบัติของโครงสร้าง
คุณสมบัติของโครงสร้างได้อธิบายไว้ด้านล่าง −
-
เป็นไปได้ที่จะคัดลอกเนื้อหาขององค์ประกอบโครงสร้างทั้งหมดของประเภทข้อมูลที่แตกต่างกันไปยังตัวแปรโครงสร้างอื่นของประเภทโดยใช้ตัวดำเนินการกำหนด
-
สำหรับการจัดการประเภทข้อมูลที่ซับซ้อน จะดีกว่าที่จะสร้างโครงสร้างภายในโครงสร้างอื่น ซึ่งเรียกว่าเป็นโครงสร้างที่ซ้อนกัน
-
เป็นไปได้ที่จะส่งผ่านโครงสร้างทั้งหมด แต่ละองค์ประกอบของโครงสร้าง และที่อยู่ของโครงสร้างไปยังฟังก์ชัน
-
นอกจากนี้ยังสามารถสร้างตัวชี้โครงสร้างได้
การประกาศโครงสร้าง
รูปแบบทั่วไปของการประกาศโครงสร้างมีดังนี้ -
datatype member1;
struct tagname{
datatype member2;
datatype member n;
}; ที่นี่ โครงสร้าง คือคีย์เวิร์ด
ชื่อแท็ก ระบุชื่อโครงสร้าง
สมาชิก1,สมาชิก2 เป็นรายการข้อมูล
ตัวอย่างเช่น
struct book{
int pages;
char author [30];
float price;
}; ตัวอย่าง
ต่อไปนี้เป็นโปรแกรม C สำหรับโครงสร้างในขอบเขตท้องถิ่น -
#include<stdio.h>
struct{
char name[20];
int age;
int salary;
char add[30];
}emp1,emp2;
int manager(){
struct{
char name[20];
int age;
int salary;
char add[50];
}manager ;
manager.age=27;
if(manager.age>30)
manager.salary=65000;
else
manager.salary=55000;
return manager.salary;
}
int main(){
printf("enter the name of emp1:");
//gets(emp1.name);
scanf("%s",emp1.name);
printf("\nenter the add of emp1:");
scanf("%s",emp1.add);
printf("\nenter the salary of emp1:");
scanf("%d",&emp1.salary);
printf("\nenter the name of emp2:");
// gets(emp2.name);
scanf("%s",emp2.name);
printf("\nenter the add of emp2:");
scanf("%s",emp2.add);
printf("\nenter the salary of emp2:");
scanf("%d",&emp2.salary);
printf("\nemp1 salary is %d",emp1.salary);
printf("\nemp2 salary is %d",emp2.salary);
printf("\nmanager salary is %d",manager());
return 0;
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
enter the name of emp1:hari enter the add of emp1:hyderabad enter the salary of emp1:4000 enter the name of emp2:lucky enter the add of emp2:chennai enter the salary of emp2:5000 emp1 salary is 4000 emp2 salary is 5000 manager salary is 55000