120 likes | 366 Views
8장: 구조체와 공용체. 구조체( Structure Type). array 와 같이 derived data type 이다. 여러 가지 항목을 가진 객체를 변수로 만들고 싶을 때 사용한다. 예를 들어, 성적 처리 프로그램에서 학생 데이터. 구조체의 선언. 우선 타입을 선언하자. 변수의 선언과는 다른 개념이다. 위의 선언은 멤버 name[], kor, eng, math 를 가지는 student 라는 struct type 의 선언이다. struct student { char name[20];
E N D
구조체(Structure Type) • array와 같이 derived data type이다. • 여러 가지 항목을 가진 객체를 변수로 만들고 싶을 때 사용한다. • 예를 들어, 성적 처리 프로그램에서 학생 데이터
구조체의 선언 • 우선 타입을 선언하자. • 변수의 선언과는 다른 개념이다. • 위의 선언은 멤버 name[], kor, eng, math를 가지는 student라는 struct type의 선언이다. struct student { char name[20]; int kor; int eng; int math; };
예제 프로그램 (1/2) #include<stdio.h> struct student{ char name[20]; int kor, eng, math; }; int main(void) { struct student class_mem; ... - struct student{ }는 struct student라는 데이터 타입의 선언이다. - struct student class_mem;은 struct student 타입의 변수 class_mem의 선언이다.
예제 프로그램 (2/2) #include<stdio.h> #include<string.h> ... int main(void) { struct student class_mem; class_mem.kor = 70; class_mem.eng = 60; ... #include<stdio.h> #include<string.h> ... int main(void) { struct student class_mem; .... strcpy(class_mem.name, “Babo”); ....
strcpy 함수 • string.h에 선언되어 있음. • 형식 • strcpy(char array(destination string), char array(source string))
구조체의 복사 • struct student tclass_mem; • tclass_mem = class_mem • class_mem의 각 멤버(name, kor, eng, math)들의 값이 tclass_mem의 각 값으로 복사된다. • 직접 하나씩 따로따로 복사해도 된다. ^^;
구조체의 초기화 • structure type 변수의 초기화는 배열의 초기화와 유사하다. card c = {13, ‘h’}; complex a[3][3] = { {{1.0, -0.1}, {2.0, 0.2}, {3.0, 0.3}}, {{4.0, -0.4}, {5.0, 0.5}, {6.0, 0.6}},}; /* 배열의 나머지 원소는 0으로 초기화 */ struct fruit frt = {“plum”, 150);
함수로의 구조체 전달 • structure type도 다른 type과 마찬가지로 함수의 인자가 될 때는 call-by-value로 전달된다. • 단, structure의 크기가 클 때는 인자를 복사하는데 시간이 많이 걸리고 공간상으로도 낭비이므로 주로 structure의 포인터를 인자로 주는 방법을 사용한다.
공용체(Union Type) • union은 다른 타입의 여러 변수들을 하나의 기억 장소에 보관함으로써 한 객체가 여러 가지 타입으로 사용될 때 기억 장소의 절약을 가져올 수 있다.
공용체의 선언 (1/2) • 멤버중 하나만을 취한다. • union • union type 임을 나타내는 키워드 • int_or_float • tag_name union int_or_float{ int i; float f; };
int i, float f • union int_or_float type의 멤버들 • union int_or_float a, b, c • union int_or_float type의 변수 a, b, c의 선언 • union int_or_float type의 크기는 int i, float f중 큰 것의 크기다. • 변수 a, b, c는 참조될 때 int i나 float f 중 어느하나로만 참조될 수 있다. 공용체의 선언 (2/2)