구조체
C/C++ 프로그래밍 언어에서 구조화 된 데이터를 처리할 때 struct를 사용하는데 이를 구조체라고 합니다. 구조화되었다는 말은 의미가 연결되어 한 덩어리로 처리하는 방식을 말합니다. 하나의 형으로만으로 데이터를 표현하기 힘들 때 사용합니다.
형태가 다른 이름, 전화번호, 주소 등을 여러 개의 배열로 관리하기 쉽게 서로 다른 형의 변수들을 하나로 묶어주기 위해 사용합니다.
형태
struct name_card {
char name[20];
char phone[20];
char addr[60];
int birthday;
};
int main(){
name_card friends;
strcpy_s(friends.name, "김갑갑");
strcpy_s(friends.phone, "010-1234-5678");
strcpy_s(friends.addr, "모현읍왕산리");
friends.birthday = 9600123;
}
결과
구조체에 원하는 값을 입출력 할 때는 구조체명.구조체멤버의 형식으로 제어 해줍니다.
구조체의 배열
구조체도 하나의 형이기 때문에 int, char와 같이 []로 배열을 선언 해줍니다.
struct name_card {
char name[20];
char phone[20];
char addr[60];
int birthday;
};
int main(){
name_card people[10];
//김갑갑의 정보를 입력
strcpy_s(people[5].name, "김갑갑");
strcpy_s(people[5].phone, "010-1234-5678");
strcpy_s(people[5].addr, "모현읍 왕산리");
people[5].birthday = 9600123;
//많은 사람의 정보 중 김갑갑의 전화 번호를 출력하시오
for (int i = 0; i < 10; i++) {
if (strcmp(people[i].name, "김갑갑") == 0) {
cout << "phone: " << people[i].phone << "\n";
break;
}
}
}
결과
for문으로 김갑갑의 이를을 가진 배열 번호를 찾고 그 배열 번호의 전화번호를 출력해줍니다.
구조체의 중첩
구조체안에 구조체를 선언해줄수도 있습니다. 더욱 자세한 정보를 입력하기 위해 사용합니다.
struct name_card2 {
char name[20];
struct phone_info {
int region, first, second;
}phone;
char addr[60];
struct birth_info {
int year, month, date;
}birth;
};
int main(){
name_card2 friends2;
friends2.phone.region = 82;
friends2.phone.first = 1234;
friends2.phone.second = 5678;
cout << "phone: " << friends2.phone.region << friends2.phone.first << friends2.phone.second << "\n";
}
결과
구조체명.구조체명.구조체멤버 형식으로 제어 가능합니다.
구조체 변수의 초기화
구조체 변수를 초기화 할 때 한 번에 초기화가 가능합니다.
struct name_card2 {
char name[20];
struct phone_info {
int region, first, second;
}phone;
char addr[60];
struct birth_info {
int year, month, date;
}birth;
};
int main(){
//초기화
name_card2 man = {
"김을을",
{82,5678,1234},
"모현면 왕산리",
{1977,07,07}
};
cout << "man.name: " << man.name << '\n';
cout << "man.phone.firs: " << man.phone.first << '\n';
cout << "man.addr: " << man.addr << '\n';
cout << "man.birth.year: " << man.birth.year << '\n';
}
결과
구조체 포인터
구조체 포인터를 이용하여 멤버를 접근할 때에는 ->를 이용합니다.
이 때 ->는 가장 높은 우선 순위를 갖습니다.
struct name_card2 {
char name[20];
struct phone_info {
int region, first, second;
}phone;
char addr[60];
struct birth_info {
int year, month, date;
}birth;
};
int main(){
//초기화
name_card2 man = {
"김을을",
{82,5678,1234},
"모현면 왕산리",
{1977,07,07}
};
name_card2 *p;
p = &man;
cout << "man.name: " << man.name << '\n';
cout << "man->name: " << p->name << '\n';
}
결과
댓글