Computer >> Máy Tính >  >> Lập trình >> lập trình C

Giải thích việc truy cập biến cấu trúc trong ngôn ngữ C

Cấu trúc là kiểu dữ liệu do người dùng xác định, được sử dụng để lưu trữ tập hợp các kiểu dữ liệu khác nhau.

Cấu trúc tương tự như một mảng. Sự khác biệt duy nhất là một mảng được sử dụng để lưu trữ các kiểu dữ liệu giống nhau trong khi cấu trúc được sử dụng để lưu trữ các kiểu dữ liệu khác nhau.

Từ khóa struct dùng để khai báo cấu trúc.

Các biến bên trong cấu trúc là các thành viên của cấu trúc.

Một cấu trúc có thể được khai báo như sau -

Struct structurename{
   //member declaration
};

Ví dụ

Sau đây là chương trình C để truy cập một biến cấu trú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);
}

Đầu ra

Khi chương trình trên được thực thi, nó tạo ra kết quả sau -

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