โครงสร้าง คือชุดของตัวแปรประเภทข้อมูลต่างๆ รวมกันเป็นชื่อเดียว
คุณสมบัติของโครงสร้าง
คุณสมบัติของโครงสร้างในภาษาซีมีดังนี้ −
-
เป็นไปได้ที่จะคัดลอกเนื้อหาขององค์ประกอบโครงสร้างทั้งหมดของประเภทข้อมูลที่แตกต่างกันไปยังตัวแปรโครงสร้างอื่นของประเภทโดยใช้ตัวดำเนินการกำหนด
-
สำหรับการจัดการประเภทข้อมูลที่ซับซ้อน จะเป็นการดีกว่าที่จะสร้างโครงสร้างภายในโครงสร้างอื่นซึ่งเรียกว่าโครงสร้างที่ซ้อนกัน
-
เป็นไปได้ที่จะส่งผ่านโครงสร้างทั้งหมด องค์ประกอบแต่ละส่วนของโครงสร้าง และที่อยู่ของโครงสร้างไปยังฟังก์ชัน
-
สามารถสร้างตัวชี้โครงสร้างได้
การประกาศและการเริ่มต้นของโครงสร้าง
รูปแบบทั่วไปของการประกาศโครงสร้างมีดังนี้ -
datatype member1;
struct tagname{
datatype member2;
datatype member n;
}; ที่นี่
- โครงสร้าง คือคีย์เวิร์ด
- ชื่อแท็ก ระบุชื่อโครงสร้าง
- สมาชิก1, สมาชิก2 เป็นรายการข้อมูล
ตัวอย่างเช่น
struct book{
int pages;
char author [30];
float price;
}; โปรแกรม
ต่อไปนี้เป็นโปรแกรม C การเรียงลำดับชื่อตามลำดับตัวอักษรโดยใช้โครงสร้าง −
#include<stdio.h>
#include<string.h>
struct tag{
char name[10];
int rno;
};
typedef struct tag node;
node s[5];
sort(int no){
int i,j;
node temp;
for(i=0;i<no-1;i++)
for(j=i+1;j<no;j++)
if(strcmp(s[i].name,s[j].name)>0){
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
void main(){
int no,i;
fflush(stdin);
printf("Enter The Number Of Students:");
scanf("%d",&no);
for(i=0;i<no;i++){
printf("Enter The Name:");
fflush(stdin);
gets(s[i].name);
printf("Enter the Roll:");
scanf("%d",&s[i].rno);
}
sort(no);
for(i=0;i<no;i++){
printf("%s\t",s[i].name);
printf("%d\n",s[i].rno);
}
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
Enter The Number of Students:5 Enter The Name:Priya Enter the Roll:3 Enter The Name:Hari Enter the Roll:5 Enter The Name:Pinky Enter the Roll:7 Enter The Name:Lucky Enter the Roll:1 Enter The Name:Krishna Enter the Roll:2 Hari 5 Krishna 2 Lucky 1 Pinky 7 Priya 3