ในภาษาซี โปรแกรมโครงสร้างคือชุดของตัวแปรประเภทข้อมูลต่างๆ ซึ่งจัดกลุ่มเข้าด้วยกันภายใต้ชื่อเดียว
การประกาศและการเริ่มต้นของโครงสร้าง
รูปแบบทั่วไปของการประกาศโครงสร้างมีดังนี้ -
datatype member1;
struct tagname{
datatype member2;
datatype member n;
}; ที่นี่
- struct คือคีย์เวิร์ด
- tagname ระบุชื่อโครงสร้าง
- member1, member2 ระบุรายการข้อมูลที่ประกอบเป็นโครงสร้าง
ตัวอย่างเช่น
struct book{
int pages;
char author [30];
float price;
}; ตัวแปรโครงสร้าง
การประกาศตัวแปรโครงสร้างมี 3 วิธี ดังนี้ −
วิธีแรก
struct book{
int pages;
char author[30];
float price;
}b; วิธีที่สอง
struct{
int pages;
char author[30];
float price;
}b; วิธีที่สาม
struct book{
int pages;
char author[30];
float price;
};
struct book b; การเริ่มต้นและการเข้าถึงโครงสร้าง
การเชื่อมโยงระหว่างสมาชิกและตัวแปรโครงสร้างถูกสร้างขึ้นโดยใช้ตัวดำเนินการสมาชิก (หรือ) ตัวดำเนินการจุด
การเริ่มต้นสามารถทำได้ด้วยวิธีต่อไปนี้ -
วิธีแรก
struct book{
int pages;
char author[30];
float price;
} b = {100, “balu”, 325.75}; วิธีที่สอง
struct book{
int pages;
char author[30];
float price;
};
struct book b = {100, “balu”, 325.75}; วิธีที่สามโดยใช้ตัวดำเนินการสมาชิก
struct book{
int pages;
char author[30];
float price;
} ;
struct book b;
b. pages = 100;
strcpy (b.author, “balu”);
b.price = 325.75; ตัวอย่าง
ต่อไปนี้เป็นโปรแกรม C สำหรับการเปรียบเทียบตัวแปรโครงสร้าง -
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;
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");
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะสร้างผลลัพธ์ต่อไปนี้ -
student2 and student3 are same 2 Bobby 167.000000