解釋 C 語言中結構變數的訪問


結構是一種使用者定義的資料型別,用於儲存不同型別的資料集合。

結構與陣列類似。唯一區別在於陣列儲存相同型別的資料,而結構儲存不同型別的資料。

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
",s1.name);    printf("The roll number of 1st student is : %d
",s1.roll);    printf("The average of 1st student is : %f
",s1.percentage);    printf("The student 1 grade is : %s and percentage of %f
",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

更新於: 2021 年 03 月 08 日

1 千+ 瀏覽次數

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告