C の構造体の配列
関連するデータやさまざまな種類のデータの大規模なセットを扱う場合、それを効率的に整理して管理することが重要です。 C プログラミングでは、配列と構造体の組み合わせ、つまり構造体の配列は、それを管理するための強力なツールを提供します。この記事では、C における構造体の配列の概念について説明します。
配列とは何ですか?
配列は、連続的なメモリ位置に格納された要素の同種のコレクションです。配列のサイズは固定されており、インデックスを使用して要素にランダムにアクセスできます。
配列の宣言
array_type array_name [size];
構造とは何ですか?
構造体は、C のユーザー定義データ型の 1 つで、さまざまな型の要素をメンバーとして含めることができます。
C での構造体の宣言
struct structure_name{ memberType memberName; ... ... }; 構造体の配列
要素が構造体型である配列は、構造体の配列と呼ばれます。一般に、プログラム内で複数の構造変数が必要な場合に便利です。
構造体の配列の必要性
従業員が 50 人いて、50 人の従業員のデータを保存する必要があるとします。そのためには、struct Employee タイプの 50 個の変数を定義し、その中にデータを保存する必要があります。ただし、50 個の変数を宣言して処理するのは簡単な作業ではありません。従業員 1,000 人のような、より大きなシナリオを想像してみましょう。
したがって、このように変数を宣言すると、これを処理することはできません。
struct Employee emp1, emp2, emp3, .. . ... . .. ... emp1000;
そのために、データ型が管理しやすい struct Employee soo となる配列を定義できます。
構造体の配列の宣言
struct structure_name array_name [number_of_elements];
構造体の配列の初期化
次の方法で構造体の配列を初期化できます。
struct structure_name array_name [number_of_elements] = { {element1_value1, element1_value2, ....}, {element2_value1, element2_value2, ....}, ...... ...... }; 同じ初期化は次のように行うこともできます。
struct structure_name array_name [number_of_elements] = { element1_value1, element1_value2 ...., element2_value1, element2_value2 ..... }; GNU C コンパイラは構造体の指定された初期化をサポートしているため、これを構造体の配列の初期化にも使用できます。
struct structure_name array_name [number_of_elements] = { {.element3 = value, .element1 = value, ....}, {.element2 = value, .elementN = value, ....}, ...... ...... }; C の構造体の配列の例
C
// C program to demonstrate the array of structures> #include> > // structure template> struct> Employee {> > char> Name[20];> > int> employeeID;> > int> WeekAttendence[7];> };> > // driver code> int> main()> {> > // defining array of structure of type Employee> > struct> Employee emp[5];> > > // adding data> > for> (> int> i = 0; i <5; i++) {> > emp[i].employeeID = i;> > strcpy> (emp[i].Name,> 'Amit'> );> > int> week;> > for> (week = 0; week <7; week++) {> > int> attendence;> > emp[i].WeekAttendence[week] = week;> > }> > }> > printf> (> '
'> );> > > // printing data> > for> (> int> i = 0; i <5; i++) {> > printf> (> 'Emplyee ID: %d - Employee Name: %s
'> ,> > emp[i].employeeID, emp[i].Name);> > printf> (> 'Attendence
'> );> > int> week;> > for> (week = 0; week <7; week++) {> > printf> (> '%d '> , emp[i].WeekAttendence[week]);> > }> > printf> (> '
'> );> > }> > > return> 0;> }> |
出力
Emplyee ID: 0 - Employee Name: Amit Attendence 0 1 2 3 4 5 6 Emplyee ID: 1 - Employee Name: Amit Attendence 0 1 2 3 4 5 6 Emplyee ID: 2 - Employee Name: Amit Attendence 0 1 2 3 4 5 6 Emplyee ID: 3 - Employee Name: Amit Attendence 0 1 2 3 4 5 6 Emplyee ID: 4 - Employee Name: Amit Attendence 0 1 2 3 4 5 6