C의 구조 배열
대규모의 관련 데이터와 다양한 데이터 유형을 처리할 때는 이를 효율적으로 구성하고 관리하는 것이 중요합니다. C 프로그래밍에서 배열과 구조의 조합, 즉 구조 배열은 이를 관리하는 강력한 도구를 제공합니다. 이번 글에서는 C 언어의 구조체 배열(Array of Structures) 개념에 대해 설명합니다.
어레이란 무엇입니까?
배열은 연속적인 메모리 위치에 저장된 동종의 요소 모음입니다. 배열의 크기는 고정되어 있으며 인덱스를 사용하여 요소에 무작위로 액세스할 수 있습니다.
배열 선언
array_type array_name [size];
구조란 무엇입니까?
구조는 다양한 유형의 요소를 멤버로 포함할 수 있는 C의 사용자 정의 데이터 유형 중 하나입니다.
C의 구조 선언
struct structure_name{ memberType memberName; ... ... }; 구조 배열
요소가 구조 유형인 배열을 구조 배열이라고 합니다. 일반적으로 프로그램에 여러 구조 변수가 필요할 때 유용합니다.
구조 배열의 필요성
직원이 50명이고 직원 50명의 데이터를 저장해야 한다고 가정합니다. 따라서 이를 위해서는 Employee 구조체 유형의 변수 50개를 정의하고 그 안에 데이터를 저장해야 합니다. 그러나 50개의 변수를 선언하고 처리하는 것은 쉬운 일이 아닙니다. 직원 1000명과 같은 더 큰 시나리오를 상상해 봅시다.
따라서 이런 식으로 변수를 선언하면 이를 처리할 수 없습니다.
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 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