解釋C語言中的結構體陣列


C程式設計中的結構體陣列是不同資料型別變數的集合,這些變數在一個名稱下組合在一起。

結構體宣告的一般形式

以下為結構體宣告

struct tagname{
   datatype member1;
   datatype member2;
   datatype member n;
};

這裡,struct 是關鍵字

    tagname 指定結構體的名稱

    member1, member2 指定構成結構體的資料項。

示例

以下示例展示了在C程式設計中使用結構體陣列的方法:

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

結構體陣列

  • C程式設計中最常見的結構體用法是結構體陣列。

  • 要宣告結構體陣列,首先必須定義結構體,然後定義該型別的陣列變數。

  • 例如:struct book b[10]; //型別為‘book’的結構體陣列,包含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 
"
, i+1);       printf(" Id is: %d
"
, record[i].id);       printf(" Name is: %s
"
, record[i].name);       printf(" Percentage is: %f

"
,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

更新於: 2023年9月6日

44K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

立即開始
廣告