8. Structures and Unions
* C Language: extensible language - Extension using macros
- Extension using user-defined data types using typedef statement, using structure
8.1 Structures
* array - aggregation of homogeneous data
* structure - Aggregation of heterogeneous data
구조체 여러 가지 구성요소를 가진 하나의 정보 단위로서 사용된다.
예제 )
학생의 성적 (학번, 성명, 이름 등 ) 책 정보 (책명, 저자, 가격 등)
데이터베이스의 레코드 개념과 다소 유사하다.
8.2 Structure template and structure variable
* structure template : 구조체의 설계 (design)
- 구조체를 어떻게 구성할 것인가를 기술할 뿐 변수 선언은 아님.
ex)
struct book {
char title[200] ; char author[100] ; fload price ; } ;
* structure variable declaration (구조체 변수의 선언)
struct book b1 ;
- 구조체 변수를 선언하여야 비로소 변수로서 사용될 메모리 공간이 확보된다.
* Simultaneous structure template and variable declaration
struct book {
{
char title[200] ; char author[100] ; fload price ; } b1 ;
structure template book 과 structure variable b1을 동시에 정의
* structure initialization ex)
struct book b1 = {
“A Book on C”,
“Al Kelley and Ira Pohl”, 1.98
} ;
* structure array
ex)
struct book b[100] ;
100개의 책을 담을 수 있는 그릇을 마련
* nested structure
구조체의 구성원으로서 구조체를 사용하는 경우 ex)
struct name {
char firstname[50];
char midname[50];
char lastname [50];
}
struct addr {
char zipcode[7] ; char addr1[100] ; char addr2[100] ; }
struct employee {
struct name ename;
struct addr eaddr ; float salary ; }
8.3 Accessing members of structure
* “.” member accessing operator
ex)
struct book b1 ;
strcpy(b1.title,”A Book on C”) ;
strcpy(b1.author,”Al Kelley and Ira Pohl”) ; b1.price = 1.98 ;
* accessing members of structure array ex)
struct book b[100] ;
printf(“ title of books are ; \ n”) ; for(i=0;i<100;i++)
{
printf(“ %d : %s \ n “, b[i].title ) ; }
* (주의) 배열의 구성원에 접근할 때 b.title[i] 가 아님에 주의
(쪽지시험)
사용자로부터 100 개의 정보에 대한 입력을 받아서 1) 총 가격과
2) 평균 가격을 계산하는 프로그램을 작성하라 단, 입력시
scanf(“%s %s %f “,…) ;
형식으로 간단히 입력 받을 수 있다고 간주한다.