解釋 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 程式 −

 線上演示

#include <stdio.h>
// Declaration of the structure candidate
struct candidate {
   int roll_no;
   char grade;
   // Array within the structure
   float marks[4];
};
// Function to displays the content of
// the structure variables
void display(struct candidate a1){
   printf("Roll number : %d
", a1.roll_no);    printf("Grade : %c
", a1.grade);    printf("Marks secured:
");    int i;    int len = sizeof(a1.marks) / sizeof(float);    // Accessing the contents of the    // array within the structure    for (i = 0; i < len; i++) {       printf("Subject %d : %.2f
",       i + 1, a1.marks[i]);    } } // Driver Code int main(){    // Initialize a structure    struct candidate A= { 1, 'A', { 98.5, 77, 89, 78.5 } };    // Function to display structure    display(A);    return 0; }

輸出

當執行以上程式時,產生以下結果 −

Roll number : 1
Grade : A
Marks secured:
Subject 1 : 98.50
Subject 2 : 77.00
Subject 3 : 89.00
Subject 4 : 78.50

更新於:19-Mar-2021

4 千次以上瀏覽

開啟您的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.