อาร์เรย์ของโครงสร้างในการเขียนโปรแกรม C คือชุดของตัวแปรประเภทข้อมูลต่างๆ ที่จัดกลุ่มเข้าด้วยกันภายใต้ชื่อเดียว
รูปแบบทั่วไปของการประกาศโครงสร้าง
การประกาศโครงสร้างมีดังนี้ -
struct tagname{
datatype member1;
datatype member2;
datatype member n;
}; ที่นี่ โครงสร้าง คือคีย์เวิร์ด
ชื่อแท็ก ระบุชื่อโครงสร้าง
สมาชิก1,สมาชิก2 ระบุรายการข้อมูลที่ประกอบเป็นโครงสร้าง
ตัวอย่าง
ตัวอย่างต่อไปนี้แสดงการใช้อาร์เรย์ของโครงสร้างในการเขียนโปรแกรม C -
struct book{
int pages;
char author [30];
float price;
}; อาร์เรย์ของโครงสร้าง
-
การใช้งานโครงสร้างที่พบบ่อยที่สุดในการเขียนโปรแกรม C คืออาร์เรย์ของโครงสร้าง
-
ในการประกาศอาร์เรย์ของโครงสร้าง ก่อนอื่นต้องกำหนดโครงสร้าง จากนั้นจึงกำหนดตัวแปรอาร์เรย์ประเภทนั้น
-
ตัวอย่างเช่น − struct book b[10]; //10 องค์ประกอบในอาร์เรย์ของโครงสร้างประเภท 'หนังสือ'
ตัวอย่าง
โปรแกรมต่อไปนี้แสดงการใช้อาร์เรย์ของโครงสร้าง
#include <stdio.h>
#include <string.h>
struct student{
int id;
char name[30];
float percentage;
};
int main(){
int i;
struct student record[2];
// 1st student's record
record[0].id=1;
strcpy(record[0].name, "Bhanu");
record[0].percentage = 86.5;
// 2nd student's record
record[1].id=2;
strcpy(record[1].name, "Priya");
record[1].percentage = 90.5;
// 3rd student's record
record[2].id=3;
strcpy(record[2].name, "Hari");
record[2].percentage = 81.5;
for(i=0; i<3; i++){
printf(" Records of STUDENT : %d \n", i+1);
printf(" Id is: %d \n", record[i].id);
printf(" Name is: %s \n", record[i].name);
printf(" Percentage is: %f\n\n",record[i].percentage);
}
return 0;
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
Records of STUDENT : 1 Id is: 1 Name is: Bhanu Percentage is: 86.500000 Records of STUDENT : 2 Id is: 2 Name is: Priya Percentage is: 90.500000 Records of STUDENT : 3 Id is: 3 Name is: Hari Percentage is: 81.500000