โครงสร้างเป็นประเภทข้อมูลที่กำหนดโดยผู้ใช้ ซึ่งใช้ในการจัดเก็บชุดข้อมูลประเภทต่างๆ ของข้อมูล
โครงสร้างคล้ายกับอาร์เรย์ ข้อแตกต่างเพียงอย่างเดียวคืออาร์เรย์ใช้เพื่อจัดเก็บประเภทข้อมูลเดียวกัน ในขณะที่โครงสร้างใช้เพื่อจัดเก็บประเภทข้อมูลที่แตกต่างกัน
คีย์เวิร์ด struct ใช้สำหรับการประกาศโครงสร้าง
ตัวแปรภายในโครงสร้างเป็นสมาชิกของโครงสร้าง
สามารถประกาศโครงสร้างได้ดังนี้ −
Struct structurename{
//member declaration
}; ตัวอย่าง
ต่อไปนี้เป็นโปรแกรม C สำหรับเข้าถึงตัวแปรโครงสร้าง -
struct book{
int pages;
float price;
char author[20];
};
Accessing structure members in C
#include<stdio.h>
//Declaring structure//
struct{
char name[50];
int roll;
float percentage;
char grade[50];
}s1,s2;
void main(){
//Reading User I/p//
printf("enter Name of 1st student : ");
gets(s1.name);
printf("enter Roll number of 1st student : ");
scanf("%d",&s1.roll);
printf("Enter the average of 1st student : ");
scanf("%f",&s1.percentage);
printf("Enter grade status of 1st student : ");
scanf("%s",s1.grade);
//Printing O/p//
printf("The name of 1st student is : %s\n",s1.name);
printf("The roll number of 1st student is : %d\n",s1.roll);
printf("The average of 1st student is : %f\n",s1.percentage);
printf("The student 1 grade is : %s and percentage of %f\n",s1.grade,s1.percentage);
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
enter Name of 1st student: Bhanu enter Roll number of 1st student: 2 Enter the average of 1st student: 68 Enter grade status of 1st student: A The name of 1st student is: Bhanu The roll number of 1st student is: 2 The average of 1st student is: 68.000000 The student 1 grade is: A and percentage of 68.000000