Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

คำอธิบายการเข้าถึงตัวแปรโครงสร้าง (Structure) ในภาษา C


โครงสร้าง (Structure) เป็นชนิดข้อมูลที่ผู้ใช้นิยามเอง ใช้จัดเก็บชุดข้อมูลที่มีชนิดข้อมูลต่างกัน

โครงสร้างคล้ายกับอาร์เรย์ ความแตกต่างคือ อาร์เรย์จัดเก็บข้อมูลชนิดเดียวกัน ส่วนโครงสร้างจัดเก็บข้อมูลชนิดต่างกัน

คีย์เวิร์ด struct ใช้สำหรับประกาศโครงสร้าง

ตัวแปรภายในโครงสร้าง เรียกว่าสมาชิกของโครงสร้าง

โครงสร้างสามารถประกาศได้ดังนี้:

struct structurename {
    // member declaration
};

ตัวอย่าง

โปรแกรม C สำหรับการเข้าถึงตัวแปรโครงสร้าง:

struct book {
    int pages;
    float price;
    char author[20];
};

// การเข้าถึงสมาชิกโครงสร้างใน C
#include <stdio.h>

// ประกาศโครงสร้าง //
struct {
    char name[50];
    int roll;
    float percentage;
    char grade[50];
} s1, s2;

void main() {
    // อ่านอินพุตจากผู้ใช้ //
    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);
    
    // พิมพ์เอาต์พุท //
    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