โครงสร้างคือชุดของตัวแปรประเภทข้อมูลต่างๆ ที่จัดกลุ่มเข้าด้วยกันภายใต้ชื่อเดียว
รูปแบบทั่วไปของการประกาศโครงสร้าง
การประกาศโครงสร้างมีดังนี้ -
struct tagname{
datatype member1;
datatype member2;
datatype member n;
}; ที่นี่ จัดโครงสร้าง คือคีย์เวิร์ด
ชื่อแท็ก ระบุชื่อโครงสร้าง
สมาชิก1 , สมาชิก2 ระบุรายการข้อมูลที่ประกอบเป็นโครงสร้าง
ตัวอย่าง
ตัวอย่างต่อไปนี้แสดงการใช้โครงสร้างที่ขอบเขตท้องถิ่น
struct book{
int pages;
char author [30];
float price;
}; ตัวอย่าง
โปรแกรมต่อไปนี้แสดงการใช้งานโครงสร้างที่ขอบเขตภายในเครื่อง
#include<stdio.h>
struct{
char name[20];
int age;
int salary;
char add[30];
}emp1,emp2;
int manager(){
struct{ //structure at local scope
char name[20];
int age;
int salary;
char add[50];
}manager ;
manager.age=27;
if(manager.age>30)
manager.salary=650000;
else
manager.salary=550000;
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:Bob enter the add of emp1:Hyderabad enter the salary of emp1:500000 enter the name of emp2:Hari enter the add of emp2:Chennai enter the salary of emp2:450000 emp1 salary is 500000 emp2 salary is 450000 manager salary is 550000