67
구구구 (Structures) 경경경경경 경경경경경경 경경경 [email protected]. kr

구조체 (Structures )

Embed Size (px)

DESCRIPTION

구조체 (Structures ). 경일대학교 컴퓨터공학과 김권양 [email protected]. 목 차. 구조체 (structure) 의 정의 구조체의 선언방법 구조체의 멤버 참조 방법 구조체의 다양한 표현 방법 구조체 변수와 함수 구조체의 여러 형태 , 사용법 구조체 사용 예. 1. 구조체 (structure) 의 정의. - PowerPoint PPT Presentation

Citation preview

Page 1: 구조체 (Structures )

구조체 (Structures)

경일대학교

컴퓨터공학과

김권양

[email protected]

Page 2: 구조체 (Structures )

목 차1.1. 구조체구조체 (structure)(structure) 의 정의의 정의2.2. 구조체의 선언방법구조체의 선언방법3.3. 구조체의 멤버 참조 방법구조체의 멤버 참조 방법4.4. 구조체의 다양한 표현 방법구조체의 다양한 표현 방법5.5. 구조체 변수와 함수구조체 변수와 함수6.6. 구조체의 여러 형태구조체의 여러 형태 , , 사용법사용법7.7. 구조체 사용 예구조체 사용 예

Page 3: 구조체 (Structures )

1. 구조체 (structure) 의 정의 A A structurestructure is a collection of one is a collection of one

or more variables, possibly of or more variables, possibly of different types, grouped together different types, grouped together under a single name for convenient under a single name for convenient handling.handling.

StructuresStructures are called “ are called “recordrecord” in ” in some language, Pascal.some language, Pascal.

Help to organize complicated data Help to organize complicated data in large program(permit a group of in large program(permit a group of related variables to be treated related variables to be treated as a as a unitunit instead of as separate entities). instead of as separate entities).

Page 4: 구조체 (Structures )

Example of a structure: Example of a structure: payroll recordpayroll record : : an employee an employee a set of attributes such as na a set of attributes such as na

me, address, social security number, salary, eme, address, social security number, salary, etc.tc.

pointpoint : a pair of coordinates : a pair of coordinates rectanglerectangle : a pair of points : a pair of points bookbook : : 제목제목 , , 저자저자 , , 출판사출판사 , , 등등 배열과 구조체 차이점배열과 구조체 차이점 :: 배열배열 : : 개개의 변수들이 모두 개개의 변수들이 모두 동일한 동일한

데이터형을데이터형을 가진다 가진다 . . 접근 접근 -> index-> index 구조체구조체 : : 개개의 변수들이 개개의 변수들이 제각기 다른 제각기 다른

데이터형을데이터형을 가질 수 있다 가질 수 있다 . . 접근 접근 -> -> 멤버명멤버명

Page 5: 구조체 (Structures )

2. 구조체의 선언방법가가 . . 구조체 형식 선언 방법구조체 형식 선언 방법 (( 선언 형식선언 형식 )) structstruct 구조체명 구조체명 {{ 데이터형 멤버명 데이터형 멤버명 1;1; 데이터형 멤버명 데이터형 멤버명 2;2; ................................ 데이터형 멤버명 데이터형 멤버명 n;n; };};

Page 6: 구조체 (Structures )

구조체는 하나의 구조체명구조체는 하나의 구조체명 (( 태그태그 )) 을 을 가질 수 있다가질 수 있다 ..

구조체 내의 변수 선언은 멤버라고 한다구조체 내의 변수 선언은 멤버라고 한다 .. 구조체 내의 멤버로 또 다른 구조체를 구조체 내의 멤버로 또 다른 구조체를

가질 수 있다가질 수 있다 .. 구조체를 선언하면 구조체의 형식만 구조체를 선언하면 구조체의 형식만

선언되고 실제로 데이터는 할당되지 선언되고 실제로 데이터는 할당되지 않으므로 구조체 형식 선언 후 구조체 않으므로 구조체 형식 선언 후 구조체 변수를 따로 선언해야 한다변수를 따로 선언해야 한다 ..

Page 7: 구조체 (Structures )

(( 사용 예사용 예 )) structstruct womanwoman { { char name[10];char name[10]; int burst;int burst; int waist;int waist; double hip;double hip; }; }; 위 예에서 위 예에서 1010 바이트의 문자 배열과 바이트의 문자 배열과 burst, burst,

waistwaist 라는 정수형 기억장소라는 정수형 기억장소 , , 또 또 hiphip 이라는 이라는 ddoubleouble 형 기억 장소들을 구성 요소로 하는 형 기억 장소들을 구성 요소로 하는 구조체 형은 정의되었지만 실제적인 기억 구조체 형은 정의되었지만 실제적인 기억 장소가 확보된 것은 아니다장소가 확보된 것은 아니다 ..

Page 8: 구조체 (Structures )

나나 . . 구조체형 변수의 선언방법구조체형 변수의 선언방법(1)(1) 구조체형을 선언하고 난후에 그 구조체를 구조체형을 선언하고 난후에 그 구조체를

갖는 변수를 선언한다갖는 변수를 선언한다 ..

(( 선언형식선언형식 ) ) structstruct 구조체명 구조체명 변수명변수명 ;; (( 사용 예사용 예 )) - - 구조체형 선언구조체형 선언 structstruct studentstudent { { char name[20];char name[20]; int int kukekuke;; int int sansusansu;; };};

Page 9: 구조체 (Structures )

- - 그 구조체로 변수 선언을 한다그 구조체로 변수 선언을 한다 .. structstruct student student haksanghaksang ; ;(2) (2) 구조체형과 변수 선언을 동시에 한다구조체형과 변수 선언을 동시에 한다 .. (( 선언형식선언형식 )) structstruct 구조체명구조체명 {{ 멤버멤버 1,1, 멤버멤버 2,........2,........ }} 변수명변수명 ;; (( 사용 예사용 예 )) structstruct studentstudent { { char name[20];char name[20]; int int kukekuke;; int int sansusansu;; } } haksanghaksang;;

Page 10: 구조체 (Structures )

(3) (3) 구조체명 없이 바로 변수를 선언한다구조체명 없이 바로 변수를 선언한다 .. (( 선언 형식선언 형식 )) structstruct { { 멤버멤버 1, 1, 멤버멤버 2, .........2, ......... }} 변수명변수명 ;; (( 사용 예사용 예 )) structstruct { { char name[20];char name[20]; int int kukekuke;; int int sansusansu;; } } haksanghaksang;; ==> ==> 이 형태는 구조체 명을 이 형태는 구조체 명을 다시 사용할 수는 다시 사용할 수는

없다없다 .. 반드시 변수명이 선언되어야 함반드시 변수명이 선언되어야 함 ..

Page 11: 구조체 (Structures )

다다 . . 구조체의 초기화 방법구조체의 초기화 방법

(1) (1) 구조체 변수 선언시 초기화 방법구조체 변수 선언시 초기화 방법 structstruct student { student { char name[20];char name[20]; int int kukekuke;; int int sansusansu;; };}; structstruct student student haksanghaksang = {" = {" 나원참나원참 ", 0, 0}", 0, 0};; * * 초기화 시에 명시적으로 지정하지 않은 초기화 시에 명시적으로 지정하지 않은

항목은 항목은 0, 0.0, ‘\0’0, 0.0, ‘\0’ 로 초기화됨로 초기화됨 !!

Page 12: 구조체 (Structures )

(2) (2) 구조체 선언시 초기화 방법구조체 선언시 초기화 방법

structstruct student { student { char name[20];char name[20]; int int kukekuke;; int int sansusansu;; } } haksanghaksang = {" = {" 나원참나원참 ", 0, 0}", 0, 0};;

Page 13: 구조체 (Structures )

(3) (3) 배열에서의 초기화 방법배열에서의 초기화 방법 structstruct student { student { char name[20];char name[20]; int int kukekuke;; int int sansusansu;; }; }; structstruct student student haksang[50]haksang[50] = { = { {"{" 나홀로나홀로 ", 0, 0}", 0, 0},, {"{" 나원참나원참 ", 0, 0}", 0, 0},, {"{" 나대로나대로 ", 0, 0}", 0, 0},, {"{" 나신하나신하 ", 0, 0} ", 0, 0} }};;

Page 14: 구조체 (Structures )

라라 . . 적용 문제적용 문제(1) (1) 다음 내용 중에서 구조체의 태그다음 내용 중에서 구조체의 태그 , ,

멤버멤버 , , 구조체 변수를 고르시오구조체 변수를 고르시오 .. structstruct new_yearsnew_years { { char jan[20];char jan[20]; char feb[20];char feb[20]; float mar;float mar; int *int *apiapi;; } } bod, calo, alicebod, calo, alice ; ;(2) (2) 구조체와 배열의 차이점을 간단하게 구조체와 배열의 차이점을 간단하게

설명하시오설명하시오 . (. ( 표현 자료와 접근 방법표현 자료와 접근 방법 ))

Page 15: 구조체 (Structures )

3. 구조체의 멤버 참조 방법가가 . . 직접 멤버 참조직접 멤버 참조 ((

도트도트 ( . ) ( . ) 연산자연산자 ))structstruct student { student { char name[20];char name[20]; int int kukekuke;; int int sansusansu;;};};structstruct student student haksanghaksang;;

/* kuke 에 95 값 배정 */haksang.kuke = 95; /* kuke 값 출력 */printf("%d",haksang.kuke);/* name 값 배정 : error */haksang.name[]=“ 정지은” ;/* correct */strcpy(haksang.name, “

정지은” )

Page 16: 구조체 (Structures )

멤버의 명칭과 변수 명칭이 동일해도 멤버의 명칭과 변수 명칭이 동일해도 지정 방법이 다르기 때문에 서로 그 지정 방법이 다르기 때문에 서로 그 이름이 충돌하지는 않는다이름이 충돌하지는 않는다 . . 예를 들면예를 들면

structstruct student student haksanghaksang ; ; int int kukekuke ; ; haksang.haksang.kukekuke = 90 ; = 90 ; kukekuke = = haksang.kukehaksang.kuke ; ; 라는 예 안에서 라는 예 안에서 kukekuke 와 와 haksang.kukehaksang.kuke

는 전혀 다른 것으로 취급된다는 전혀 다른 것으로 취급된다 ..

Page 17: 구조체 (Structures )

(( 적용 예문적용 예문 )) /* /* 성적출력 프로그램 성적출력 프로그램 */*/#include <stdio.h>#include <stdio.h>#include <#include <string.h>string.h>void main() {void main() { structstruct student student haksanghaksang ; ;

strcpystrcpy ( (haksang.name, "haksang.name, " 나홀로나홀로 ") ;") ; haksang.kukehaksang.kuke = 99 ; = 99 ; haksang.sansuhaksang.sansu = 98 ; = 98 ; printfprintf (" (" 이름 이름 : %s",haksang.name) ;: %s",haksang.name) ; printfprintf (" (" 국어 국어 : %d",haksang.kuke) ;: %d",haksang.kuke) ; printfprintf (" (" 산수 산수 : %d",haksang.sansu) ;: %d",haksang.sansu) ; }}

Page 18: 구조체 (Structures )

나나 . . 포인터를 이용한 구조체 멤버 참조포인터를 이용한 구조체 멤버 참조 (( 간접 간접 멤버 참조 멤버 참조 :: 애로우애로우 (->)(->) 연산자연산자 ))

structstruct student student haksanghaksang;; structstruct student student *ptr*ptr=&=&haksanghaksang;; **ptr.kukeptr.kuke = 99; /* Error : *(ptr.kuke) */ = 99; /* Error : *(ptr.kuke) */ (*ptr).kuke(*ptr).kuke = 99; /* Correct */ = 99; /* Correct */ ptr->kukeptr->kuke = 99; /* Correct */ = 99; /* Correct */

구조체포인터변수 멤버명 or(* 구조체포인터변수 ). 멤버명

Page 19: 구조체 (Structures )

(( 적용 예문적용 예문 : arrow operator: arrow operator)) /* /* 성적출력 프로그램 성적출력 프로그램 */*/#include <stdio.h>#include <stdio.h>#include <#include <string.h>string.h>void main() {void main() { structstruct student student haksanghaksang;; structstruct student *ptr = & student *ptr = &haksanghaksang;;

strcpystrcpy (ptr->name," (ptr->name," 나홀로나홀로 ");"); ptr->ptr->kukekuke = 99; = 99; (*ptr).(*ptr).sansusansu = 98; = 98; printfprintf (" (" 이름 이름 : %s",ptr->name);: %s",ptr->name); printfprintf (" (" 국어 국어 : %d",ptr->kuke);: %d",ptr->kuke); printfprintf (" (" 산수 산수 : %d",ptr->sansu);: %d",ptr->sansu);}}

Page 20: 구조체 (Structures )

4. 구조체의 다양한 표현 방법가가 . . 구조체의 연산구조체의 연산 일반 변수일반 변수 :: if (a>b) /*ok */if (a>b) /*ok */ 구조체구조체 :: structstruct student student haksang1, haksang2 ;haksang1, haksang2 ; .......................... if (if (haksang1 > haksang2) /* Incorrect */haksang1 > haksang2) /* Incorrect */ if (haksang.kuke > haksang.sansu ) /* ok if (haksang.kuke > haksang.sansu ) /* ok

*/*/

Page 21: 구조체 (Structures )

(1) (1) 구조체간의 복사 구조체간의 복사 (ANSI-C (ANSI-C 확장확장 )) 구조체를 구조체를 한꺼번에 복사할한꺼번에 복사할 수 있다 수 있다 . . 구조체 구조체

안에 문자열이 있어도 그대로 복사가 가능하다안에 문자열이 있어도 그대로 복사가 가능하다 . . (( 예문예문 ))structstruct person { person { char name[20], sexchar name[20], sex; ; int age;int age;} st1, st2 = {“} st1, st2 = {“ 김문수”김문수” ,’M’,17};,’M’,17};................................st1 = st2;st1 = st2;

두 구조체가 두 구조체가 호환 가능하여야호환 가능하여야 한다 한다 ! (person)! (person)

Page 22: 구조체 (Structures )

(2) (2) 구조체의 주소를 추출구조체의 주소를 추출(( 예문예문 )) structstruct student student haksanghaksang ; ; structstruct student *ptr ; student *ptr ; ptr = &ptr = &haksanghaksang;; /* /* haksanghaksang 의 주소값을 추출 의 주소값을 추출 */*/

Page 23: 구조체 (Structures )

(3) (3) 멤버를 참조멤버를 참조 멤버참조 연산자를 이용하여 구조체의 멤버참조 연산자를 이용하여 구조체의

멤버를 개별적으로 지정 할 수 있다멤버를 개별적으로 지정 할 수 있다 ..

(( 예문예문 )) structstruct student student haksanghaksang ; ; structstruct student *ptr ; student *ptr ; ptr = &ptr = &haksanghaksang ; ; haksang.kukehaksang.kuke = 99; = 99; ptr->ptr->sansusansu = 98 ; = 98 ;

Page 24: 구조체 (Structures )

나나 . . 구조체의 배열과 포인터 표현 방법구조체의 배열과 포인터 표현 방법

structstruct student student haksanghaksang[100]; /* [100]; /* 배열로 선언 배열로 선언 */*/ structstruct student *ptr; /* student *ptr; /* 포인터로 선언 포인터로 선언 */*/ ptr = ptr = haksanghaksang; ; /* ptr/* ptr 에 에 haksang[]haksang[] 의 선두번지값을 대입 의 선두번지값을 대입 */*/ ptr->ptr->kukekuke = 99; = 99; /* /* 멤버참조 멤버참조 haksang[0].kuke=99haksang[0].kuke=99 와 동일 와 동일 */*/ ++ptr; /* ++ptr; /* 포인터 포인터 ptrptr 를 를 11 증가 시키면 증가 시키면 */*/ ptr->ptr->kuke=99;kuke=99; /* /* 배열이 배열이 11 증가 한것과 동일증가 한것과 동일 즉 즉 haksang[1].kuke=99 ;haksang[1].kuke=99 ; 동일 동일 */*/

Page 25: 구조체 (Structures )

다다 . . 적용 예제적용 예제(1) (1) 다음의 자료를 구조체 배열에 대입하고 다음의 자료를 구조체 배열에 대입하고

화면에 출력하는 프로그램을 작성하시오화면에 출력하는 프로그램을 작성하시오 .(.(제출제출 !)!)

NameName Sex Age Address Sex Age Address홍길동 홍길동 M 30 M 30 서울시 마포구 당상동서울시 마포구 당상동나원참 나원참 F 35 F 35 부산시 영도구 영동부산시 영도구 영동신나라 신나라 M 42 M 42 대구시 북구 침산동대구시 북구 침산동

(2) (2) 학생들의 생년월일이 빠른 순서로 학생들의 학생들의 생년월일이 빠른 순서로 학생들의 관련자료를 출력하는 프로그램을 작성하시오관련자료를 출력하는 프로그램을 작성하시오 . . 원래의 자료는 임의의 작성하되 생년월일과 원래의 자료는 임의의 작성하되 생년월일과 무관한 순서로 되어 있다고 가정한다무관한 순서로 되어 있다고 가정한다 ..

Page 26: 구조체 (Structures )

struct struct personperson { { char name[10];char name[10]; char sex;char sex; int age;int age; char addr[30];char addr[30];} person1[3] = {} person1[3] = { {“{“ 홍길동”홍길동” ,’M’,30,”,’M’,30,” 서울시 마포구 당상동”서울시 마포구 당상동” },}, {“{“ 나원참”나원참” ,’F’,35,”,’F’,35,” 부산시 영도구 영동”부산시 영도구 영동” },}, {“{“ 신나라”신나라” ,’M’,42,”,’M’,42,” 대구시 북구 침산동”대구시 북구 침산동” }}};};struct struct personperson *pptr; *pptr;pptr = person1;pptr = person1;

Page 27: 구조체 (Structures )

5. 구조체 변수와 함수가가 . . 구조체를 함수로 전달하는 방법구조체를 함수로 전달하는 방법1)1) 실인자로 구조체 전체 전달실인자로 구조체 전체 전달 (ANSI-C)(ANSI-C)2)2) 실인자로 구조체 멤버 전달실인자로 구조체 멤버 전달3)3) 주소에 의한 전달주소에 의한 전달 (( 포인터포인터 ))

1), 2) 1), 2) 방식은 방식은 call-by-valuecall-by-value 에 의해 실인자의에 의해 실인자의 값이 함수의 인자로 복사되기 때문에 인수의값이 함수의 인자로 복사되기 때문에 인수의독립성이 유지되어 프로그램이 안전해지나 구조독립성이 유지되어 프로그램이 안전해지나 구조체가 큰 경우 복사본 생성을 위한 체가 큰 경우 복사본 생성을 위한 overheadoverhead 로 로 실행속도를 감소시킨다실행속도를 감소시킨다 ..

Page 28: 구조체 (Structures )

(( 적용 예문적용 예문 )) /* /* 함수에 구조체를 전달하는 프로그램 함수에 구조체를 전달하는 프로그램 */*/#include <#include <stdio.h>stdio.h>structstruct woman { /* woman { /* 구조체 선언부분을 먼저 구조체 선언부분을 먼저 */*/ char name[20];char name[20]; int burst;int burst; int hip;int hip;};};/* /* 함수프로토타입 함수프로토타입 */*/void void disp1(structdisp1(struct woman woman str); str); void void disp2(structdisp2(struct woman * woman *str) ;str) ;

Page 29: 구조체 (Structures )

void main ( ) {void main ( ) { structstruct woman woman miinmiin = {" = {" 한몸매한몸매 ", 34, 35}", 34, 35};; disp1(miin) ; /* disp1(miin) ; /* 값에 의한 전달 값에 의한 전달 */*/ disp2(&miin) : /* disp2(&miin) : /* 주소에 의한 전달 주소에 의한 전달 */*/ disp3(miin.name,miin,burst,miin.hip); /* disp3(miin.name,miin,burst,miin.hip); /* 멤버 멤버 */*/} } void void disp1(structdisp1(struct woman woman str) {str) { printf("%s %d %d ",str.name, str.burst, str.hip) ;printf("%s %d %d ",str.name, str.burst, str.hip) ; }} void void disp2(structdisp2(struct woman * woman *str) {str) { printf("%s %d %d ",str->name, str->burst, str->hip);printf("%s %d %d ",str->name, str->burst, str->hip); }}void void disp3disp3(char *name, int bst, int hp) {(char *name, int bst, int hp) {printf(“%s %d %d”,name,bst,hp);printf(“%s %d %d”,name,bst,hp);}}

Page 30: 구조체 (Structures )

나나 . . 함수에서 구조체를 전달 받는 방법함수에서 구조체를 전달 받는 방법 (( 적용 예문적용 예문 ))#include <#include <stdio.h>stdio.h>#include <#include <string.h>string.h>structstruct woman { woman { char name [20] ;char name [20] ; int burst ;int burst ; int hip ;int hip ;};}; structstruct woman woman set(char set(char irum[] , int buirum[] , int bu , int hi ); , int hi );void void dispdisp ( (structstruct woman woman str) ;str) ;

Page 31: 구조체 (Structures )

void main( ) {void main( ) { structstruct woman woman miinmiin ; ; miinmiin = set (" = set (" 한몸매한몸매 ", 36, 38) ;", 36, 38) ; dispdisp ( (miin) ;miin) ;} } structstruct woman set(char woman set(char irum[], int bu, int hi) {irum[], int bu, int hi) { structstruct woman da ; woman da ; strcpystrcpy ( (da.nameda.name , ,irum)irum) da.burstda.burst = = bu;bu; da.hipda.hip = hi ; = hi ; return da ;return da ;}}void void dispdisp ( (structstruct woman woman str) {str) { printf("%s %d %d ", str.name, str.burst, str.hip) ;printf("%s %d %d ", str.name, str.burst, str.hip) ; }}

Page 32: 구조체 (Structures )

6. 구조체의 여러 형태 , 사용법가가 . . 중첩된 구조체중첩된 구조체 structstruct book { book { char name[100] ; /* char name[100] ; /* 책이름 책이름 */*/ int o_price; /* int o_price; /* 원가 원가 */*/ int d_price; /* int d_price; /* 할인가 할인가 */*/ int r_price; /* int r_price; /* 정상 판매가 정상 판매가 */*/ int jeagoint jeago; /* ; /* 재고 수량 재고 수량 */*/ };}; structstruct book book fictionfiction ; ;

Page 33: 구조체 (Structures )

* Nested Structures * Nested Structures structstruct gagukgaguk { { int o_price ;int o_price ; int d_price ;int d_price ; int r_price ;int r_price ; };}; structstruct book { book { char name[100];char name[100]; structstruct gagukgaguk price price; /* ; /* 구 조 체 내 에 또 구 조 체 내 에 또

구조체 구조체 */*/ int int jeagojeago ; ; };}; structstruct book book fictionfiction;;

Page 34: 구조체 (Structures )

사용 예사용 예 ))structstruct book book1; book book1;structstruct book * book *strstr = book1; = book1;

/* /* 일반변수일 경우 정가를 참조하는 예문 일반변수일 경우 정가를 참조하는 예문 */*/ book1.price.r_price = 13000 ; book1.price.r_price = 13000 ; /* /* 포인터일 경우 정가를 참조하는 예문 포인터일 경우 정가를 참조하는 예문 */*/ str->price.r_price = 13000;str->price.r_price = 13000;/* error */ /* error */ str->price->r_price = 13000;str->price->r_price = 13000;

Page 35: 구조체 (Structures )

중첩된 구조체의 초기화중첩된 구조체의 초기화 structstruct person { person { char name[20], sex, tele[12];char name[20], sex, tele[12]; structstruct birth_date { birth_date { int day;int day; int month;int month; int year;int year; }} } } clubclub = {“ = {“ 홍길동”홍길동” , ‘M’, ‘850-7287’, 8, 5, 197, ‘M’, ‘850-7287’, 8, 5, 197

9}; 9}; oror structstruct person person clubclub = {“ = {“ 홍길동”홍길동” , ‘M’, ‘850-728, ‘M’, ‘850-728

7’, {8, 5, 1979}}; 7’, {8, 5, 1979}};

Page 36: 구조체 (Structures )

나나 . . 자기참조 구조체자기참조 구조체 : : 자기 자신을 가리키는 구조체를 말한다자기 자신을 가리키는 구조체를 말한다 . .

구조체는 중첩이 가능하므로 자기자신을 구조체는 중첩이 가능하므로 자기자신을 포함시킨 것인데 일반적인 포함시킨 것인데 일반적인 포인터 형으로포인터 형으로 선언되어야 하며 자료구조 측면에서 매우 선언되어야 하며 자료구조 측면에서 매우 중요한 의미를 갖는다중요한 의미를 갖는다

structstruct sungjuksungjuk { { char name [50] ;char name [50] ; int aver ;int aver ; int total ;int total ; structstruct sungjuksungjuk kamokkamok ; ; }; /* Wrong */ }; /* Wrong */

Page 37: 구조체 (Structures )

structstruct sungjuksungjuk { { char name [50] ;char name [50] ; int aver ;int aver ; int total ;int total ; structstruct sungjuksungjuk **kamokkamok ; ; };};* * 자기참조자기참조 구조체는 구조체는 "" 자신 안에 자신을 자신 안에 자신을

가리키는 포인터를 포함시킨 것가리키는 포인터를 포함시킨 것 ""

Page 38: 구조체 (Structures )

structstruct robot { robot { int head;int head; int arms[2];int arms[2]; int *finger;int *finger; structstruct robot *next; robot *next;} } mazingamazinga , , teagenboy, robocop[5];teagenboy, robocop[5];

Page 39: 구조체 (Structures )

void main( ) {void main( ) { .............................. ................................ /* /* 한방향으로 연결고리 만들기 한방향으로 연결고리 만들기 */*/ mazinga.nextmazinga.next = & = &teagenboyteagenboy ; ; teagenboy.nextteagenboy.next = & = &robocop[0] ;robocop[0] ; robocop[0].next = &robocop[4] ;robocop[0].next = &robocop[4] ; robocop[4].next = 0x00 /* robocop[4].next = 0x00 /* 종료 종료 */*/

Page 40: 구조체 (Structures )

/* /* teagenboyteagenboy 를 삭제할 경우 를 삭제할 경우 */*/ ........................................................ mazinga.nextmazinga.next = & = &robocop[0] ;robocop[0] ; robocop[0].next = &robocop[4] ;robocop[0].next = &robocop[4] ;/* /* robocop[1]robocop[1] 를 를 robocop[0]robocop[0] 다 음 에 삽입 할 다 음 에 삽입 할

경우 경우 */*/ .............................................................. mazinga.nextmazinga.next = & = &robocop[0] ;robocop[0] ; robocop[0].next = &robocop[1] ;robocop[0].next = &robocop[1] ; robocop[1].next = &robocop[4] ;robocop[1].next = &robocop[4] ; ............................................................

Page 41: 구조체 (Structures )

/* /* 양방향 양방향 linked list */ linked list */ structstruct robot { robot { int head;int head; int arms[2];int arms[2]; int *finger;int *finger; structstruct robot *before; robot *before; structstruct robot *next; robot *next;} } mazingamazinga , , teagenboy, robocop[5];teagenboy, robocop[5];

Page 42: 구조체 (Structures )

( 응용 예제 : 자기참조 구조체 ) #include <#include <stdio.h>stdio.h> #include <#include <stdlib.h>stdlib.h> #include <#include <string.h>string.h>

structstruct human { human { char char irumirum [30] ; [30] ; int int nainai ; ; structstruct human *next ; human *next ; };}; void main( ) {void main( ) {structstruct human human inganingan ; ;structstruct human *start=& human *start=&inganingan ; ;structstruct human *i_data ; human *i_data ;structstruct human *work ; human *work ;char char irumirum [30] = " ", [30] = " ", buf[10] ;buf[10] ;int int nainai ; ;start = &start = &inganingan ; ;start->next=NULL;start->next=NULL;

while(1) {while(1) {

printf("printf(" 이름 이름 : ") ;: ") ; gets(gets(irum) ;irum) ; if(if(strcmp(irum,"") == 0) break ;strcmp(irum,"") == 0) break ; printf("printf(" 나이 나이 : ") ;: ") ; gets(gets(buf) ; nai=atoi(buf) ;buf) ; nai=atoi(buf) ; i_data=(structi_data=(struct human *) human *)malloc(sizeof(strumalloc(sizeof(stru

ctct human)) ; human)) ; /* /* 구조체 구조체 11 개분의 메모리를 확보 개분의 메모리를 확보 */*/ if (i_data==NULL) {if (i_data==NULL) { printfprintf (" ("메모리를 줄 수 없습니다메모리를 줄 수 없습니다 ") ;") ; exit (1) ;exit (1) ; }} strcpy(i_data->irum,irum) ; /* strcpy(i_data->irum,irum) ; /* 확 보 한 확 보 한

구조체에 이름과 나이를 설정 구조체에 이름과 나이를 설정 */*/ i_data->i_data->nainai = = nainai ; ;

Page 43: 구조체 (Structures )

for(work=for(work=start;work->next != NULL; worstart;work->next != NULL; work=work->next) {k=work->next) {

if(if(nainai < work->next-> < work->next->nainai i_data->next=work->next ;i_data->next=work->next ; work->next=i_data ;work->next=i_data ; break ;break ; } } }} if(work->next==NULL) {if(work->next==NULL) { i_data->next = NULL ;i_data->next = NULL ; work->next = i_data ;work->next = i_data ; } }

for (work=start->next; work !=NULL ; wofor (work=start->next; work !=NULL ; work = work->next) rk = work->next)

printf("%s %d",work->irum,wprintf("%s %d",work->irum,work->nai) ;ork->nai) ;

Page 44: 구조체 (Structures )

Dynamic Allocation

All of the variables in every program up to this point haAll of the variables in every program up to this point have been ve been static variablesstatic variables.(Actually, some of them have .(Actually, some of them have been been automaticautomatic and were and were dynamically allocateddynamically allocated for yo for you by the system.u by the system.

We will study some dynamically allocated variables. TWe will study some dynamically allocated variables. They are variables that do not exist when the program ihey are variables that do not exist when the program is loaded, but are s loaded, but are created dynamicallycreated dynamically as they are nee as they are needed while the program is running. It is possible, using ded while the program is running. It is possible, using these techniques, to create as many variables as neethese techniques, to create as many variables as needed, use them, and ded, use them, and deallocatedeallocate their memory space for their memory space for reuse by other variablesreuse by other variables..

Page 45: 구조체 (Structures )

#include "stdio.h" #include "stdio.h" #include "string.h“#include "string.h“#include "stdlib.h“ /* malloc */#include "stdlib.h“ /* malloc */structstruct animal { animal { char name[25];char name[25]; char breed[25]; char breed[25]; int age;int age; } } *pet1, *pet2, *pet3*pet1, *pet2, *pet3;;

void main() {void main() { pet1 = (struct animal *)malloc(sizeof(struct animal));pet1 = (struct animal *)malloc(sizeof(struct animal)); strcpy(pet1->name, "General");strcpy(pet1->name, "General"); strcpy(pet1->breed, "Mixed Breed"); strcpy(pet1->breed, "Mixed Breed"); pet1->age = 1; pet1->age = 1; pet2 = pet1; /* pet2 now points to the above data structure */ pet2 = pet1; /* pet2 now points to the above data structure */

Page 46: 구조체 (Structures )

pet1 = (struct animal *)malloc(sizeof(struct animal)); pet1 = (struct animal *)malloc(sizeof(struct animal)); strcpy(pet1->name, "Frank"); strcpy(pet1->name, "Frank"); strcpy(pet1->breed, "Labrador Retriever");strcpy(pet1->breed, "Labrador Retriever");pet1->age = 3;pet1->age = 3;pet3 = (struct animal *)malloc(sizeof(struct animal));pet3 = (struct animal *)malloc(sizeof(struct animal));strcpy(pet3->name, "Krystal");strcpy(pet3->name, "Krystal");strcpy(pet3->breed, "German Shepherd"); strcpy(pet3->breed, "German Shepherd"); pet3->age = 4; /* now print out the data described above */pet3->age = 4; /* now print out the data described above */printf("%s is a %s, and is %d years old.\n", pet1->name, petprintf("%s is a %s, and is %d years old.\n", pet1->name, pet

1->breed, pet1->age);1->breed, pet1->age);printf("%s is a %s, and is %d years old.\n", pet2->name, petprintf("%s is a %s, and is %d years old.\n", pet2->name, pet

2->breed, pet2->age); 2->breed, pet2->age); printf("%s is a %s, and is %d years old.\n", pet3->name, petprintf("%s is a %s, and is %d years old.\n", pet3->name, pet

3->breed, pet3->age);3->breed, pet3->age);

Page 47: 구조체 (Structures )

pet1 = pet3;pet1 = pet3;/* pet1 now points to the same structure that */ /* pet1 now points to the same structure that */ /* pet3 points to *//* pet3 points to */free(pet3); /* this frees up one structure */free(pet3); /* this frees up one structure */free(pet2); /* this frees up one more structure */free(pet2); /* this frees up one more structure *//* free(pet1); this cannot be done, see explanation in te/* free(pet1); this cannot be done, see explanation in te

xt */ } xt */ }

/* Result of execution /* Result of execution Frank is a Laborador Retriever, and is 3 years old. Frank is a Laborador Retriever, and is 3 years old. General is a Mixed Breed, and is 1 years old. General is a Mixed Breed, and is 1 years old. Krystal is a German Shepherd, and is 4 years old. Krystal is a German Shepherd, and is 4 years old. */ */

Page 48: 구조체 (Structures )
Page 49: 구조체 (Structures )

(( 참고용 예제참고용 예제 )) /* /* 화면에 현재시간을 나타내는 프로그램 화면에 현재시간을 나타내는 프로그램 */*/ #include <stdio.h>#include <stdio.h>#include <#include <time.h>time.h>void main( ) {void main( ) { time_t t;time_t t; structstruct tmtm * *struct_t ;struct_t ; char *string ;char *string ; time (&t) ;time (&t) ; struct_t = localtime(&t);struct_t = localtime(&t); string = string = asctime(struct_t) ;asctime(struct_t) ; printfprintf ("%s", string) ; ("%s", string) ; }}

Page 50: 구조체 (Structures )

다다 . . 비트필드비트필드 ( bit - field) ( bit - field) 구조체구조체 (1) (1) 비트필드 구조체란비트필드 구조체란 ?? 프로그램을 작성하다 보면 가끔은 프로그램을 작성하다 보면 가끔은 flagflag레지스터 같은 것을 직접 조작할 필요성이 레지스터 같은 것을 직접 조작할 필요성이 있을 때가 있다있을 때가 있다 . . 그런데 이런 것들은 그런데 이런 것들은 전 부 비트 단 위 로 조 작 되 기 때 문 에 전 부 비트 단 위 로 조 작 되 기 때 문 에 지금까지 데이터를 취급하던 지금까지 데이터를 취급하던 intint 형형 , char, char형 등의 데이터 처리 단위가 다양하지 형 등의 데이터 처리 단위가 다양하지 않아도 된다않아도 된다 . . 이런 필요성 때문에 형식은 이런 필요성 때문에 형식은 구조체를 갖추고 있고 조작 단위는 비트 구조체를 갖추고 있고 조작 단위는 비트 단 위 로 되 어 있 는 것 이 비트필드 단 위 로 되 어 있 는 것 이 비트필드 구조체이다구조체이다 ..

Page 51: 구조체 (Structures )

(2) (2) 선언 및 참조 방법선언 및 참조 방법 데이터형 멤버명 데이터형 멤버명 : : 비트 폭 비트 폭 ;; (( 선언 예문선언 예문 )) structstruct bitgujobitgujo { { unsigned int busy : 1;unsigned int busy : 1; int ready : 2;int ready : 2; unsigned int send : 3;unsigned int send : 3; } } dataflagdataflag ; ;

Page 52: 구조체 (Structures )

(3) (3) 메모리 구조메모리 구조데이터형 데이터형 (( 멤버이름없음멤버이름없음 ) : 0 ;) : 0 ; structstruct datemidatemi { { int weekday : 3 ;int weekday : 3 ; int year : 7 ;int year : 7 ; int month : 4 ;int month : 4 ; int day : 5 ;int day : 5 ; int int kiyumkiyum : 1 ; : 1 ; } } structstruct datejidateji { { int weekday : 3 ;int weekday : 3 ; int year : 7 ;int year : 7 ; int month : 4 ;int month : 4 ; int : 0 ;int : 0 ; int day : 5 ;int day : 5 ; int int kiyumkiyum : 1 ; : 1 ; }}

Page 53: 구조체 (Structures )

7. 구조체 사용 예1) A SINGLE COMPOUND VARIABLE 1) A SINGLE COMPOUND VARIABLE #include "stdio.h" #include "stdio.h" structstruct { { char initial; /* last name initial */ char initial; /* last name initial */ int age; /* childs age */ int age; /* childs age */ int grade; /* childs grade in school */int grade; /* childs grade in school */ } } boy, girlboy, girl;;

void main() { void main() { boy.initial = 'R';boy.initial = 'R'; boy.age = 15;boy.age = 15; boy.grade = 75;boy.grade = 75;

Page 54: 구조체 (Structures )

girl.age = boy.age - 1; /* she is one year younger */ girl.age = boy.age - 1; /* she is one year younger */ girl.grade = 82;girl.grade = 82; girl.initial = 'H'; girl.initial = 'H'; printf("%c is %d years old and got a grade of %d\n", gprintf("%c is %d years old and got a grade of %d\n", g

irl.initial, girl.age, girl.grade);irl.initial, girl.age, girl.grade); printf("%c is %d years old and got a grade of %d\n", bprintf("%c is %d years old and got a grade of %d\n", b

oy.initial, boy.age, boy.grade); oy.initial, boy.age, boy.grade); } } /* Result of execution /* Result of execution H is 14 years old and got a grade of 82H is 14 years old and got a grade of 82 R is 15 years old and got a grade of 75R is 15 years old and got a grade of 75 */ */

Page 55: 구조체 (Structures )

- ASSIGNING VALUES TO THE ASSIGNING VALUES TO THE VARIABLES VARIABLES

Page 56: 구조체 (Structures )

2) AN ARRAY OF STRUCTURES 2) AN ARRAY OF STRUCTURES

#include "stdio.h“#include "stdio.h“struct {struct { char initial;char initial; int age; int age; int grade;int grade; } kids[12];} kids[12];

void main() {void main() { int index;int index; for (index = 0 ; index < 12 ; index++) { for (index = 0 ; index < 12 ; index++) { kids[index].initial = 'A' + index;kids[index].initial = 'A' + index; kids[index].age = 16;kids[index].age = 16; kids[index].grade = 84;kids[index].grade = 84; } }

Page 57: 구조체 (Structures )

kids[3].age = kids[5].age = 17; kids[3].age = kids[5].age = 17; kids[2].grade = kids[6].grade = 92;kids[2].grade = kids[6].grade = 92; kids[4].grade = 57; kids[4].grade = 57; kids[10] = kids[4];kids[10] = kids[4]; /* Structure assignment */ /* Structure assignment */ for (index = 0 ; index < 12 ; index++)for (index = 0 ; index < 12 ; index++) printf("%c is %d years old and got a grade of %d\n",printf("%c is %d years old and got a grade of %d\n", kids[index].initial, kids[index].age, kids[index].grade);kids[index].initial, kids[index].age, kids[index].grade); } } /* Result of execution /* Result of execution A is 16 years old and got a grade of 84 G is 16 years old and got a grade of 92 A is 16 years old and got a grade of 84 G is 16 years old and got a grade of 92 B is 16 years old and got a grade of 84 H is 16 years old and got a grade of 84 B is 16 years old and got a grade of 84 H is 16 years old and got a grade of 84 C is 16 years old and got a grade of 92 I is 16 years old and got a grade of 84 C is 16 years old and got a grade of 92 I is 16 years old and got a grade of 84 D is 17 years old and got a grade of 84 J is 16 years old and got a grade of 84 D is 17 years old and got a grade of 84 J is 16 years old and got a grade of 84 E is 16 years old and got a grade of 57 E is 16 years old and got a grade of 57 E is 16 years old and got a grade of 57 E is 16 years old and got a grade of 57 F is 17 years old and got a grade of 84 L is 16 years old and got a grade of 84 F is 17 years old and got a grade of 84 L is 16 years old and got a grade of 84 */ */

Page 58: 구조체 (Structures )

3) USING POINTERS AND STRUCTURES TOGETH3) USING POINTERS AND STRUCTURES TOGETHER ER

#include "stdio.h" #include "stdio.h" structstruct { { char initial;char initial; int age; int age; int grade; int grade; } } kids[12], *point, extra; kids[12], *point, extra;

void main() {void main() { int index;int index; for (index = 0 ; index < 12 ; index++) {for (index = 0 ; index < 12 ; index++) { point = kids + index; point = kids + index; point->initial = 'A' + index; point->initial = 'A' + index; point->age = 16; point->age = 16; point->grade = 84;point->grade = 84; } }

Page 59: 구조체 (Structures )

kids[3].age = kids[5].age = 17; kids[3].age = kids[5].age = 17; kids[2].grade = kids[6].grade = 92;kids[2].grade = kids[6].grade = 92; kids[4].grade = 57; kids[4].grade = 57; for (index = 0 ; index < 12 ; index++) {for (index = 0 ; index < 12 ; index++) { point = kids + index; point = kids + index; printf("%c is %d years old and got a grade of %dprintf("%c is %d years old and got a grade of %d

\n", \n", (*point).initial, kids[index].age, point->grade);(*point).initial, kids[index].age, point->grade); }} extra = kids[2]; /* Structure assignment */ extra = kids[2]; /* Structure assignment */ extra = *point; /* Structure assignment */ extra = *point; /* Structure assignment */ } } /* Result of execution /* Result of execution A is 16 years old and got a grade of 84A is 16 years old and got a grade of 84 B is 16 years old and got a grade of 84 B is 16 years old and got a grade of 84 C is 16 years old and got a grade of 92 C is 16 years old and got a grade of 92 ……. */ . */

Page 60: 구조체 (Structures )
Page 61: 구조체 (Structures )

4) NESTED AND NAMED STRUCTURES 4) NESTED AND NAMED STRUCTURES #include "stdio.h" #include "stdio.h" #include "string.h“#include "string.h“structstruct person { person { char name[25];char name[25]; int age; int age; char status; /* M = married, S = single */ char status; /* M = married, S = single */ }; }; structstruct alldat { alldat { int grade;int grade; struct person descrip; struct person descrip; char lunch[25]; char lunch[25]; };};

Page 62: 구조체 (Structures )

void main() {void main() { struct alldat student[53]; struct alldat student[53]; struct alldat teacher, sub;struct alldat teacher, sub; teacher.grade = 94; teacher.grade = 94; teacher.descrip.age = 34;teacher.descrip.age = 34; teacher.descrip.status = 'M'; teacher.descrip.status = 'M'; strcpy(teacher.descrip.name, "Mary Smith");strcpy(teacher.descrip.name, "Mary Smith"); strcpy(teacher.lunch, "Baloney sandwich"); strcpy(teacher.lunch, "Baloney sandwich"); sub.descrip.age = 87;sub.descrip.age = 87; sub.descrip.status = 'M';sub.descrip.status = 'M'; strcpy(sub.descrip.name, "Old Lady Brown"); strcpy(sub.descrip.name, "Old Lady Brown"); sub.grade = 73; sub.grade = 73; strcpy(sub.lunch, "Yogurt and toast"); strcpy(sub.lunch, "Yogurt and toast"); student[1].descrip.age = 15;student[1].descrip.age = 15; student[1].descrip.status = 'S'; student[1].descrip.status = 'S'; strcpy(student[1].descrip.name, "Billy Boston"); strcpy(student[1].lunch, strcpy(student[1].descrip.name, "Billy Boston"); strcpy(student[1].lunch,

"Peanut Butter"); "Peanut Butter"); student[1].grade = 77; student[1].grade = 77; student[7].descrip.age = 14; student[7].descrip.age = 14; student[12].grade = 87; student[12].grade = 87; } }

Page 63: 구조체 (Structures )
Page 64: 구조체 (Structures )

예상문제 ( 구조체 )

1.1. 다음 구조체 자료형 선언에 따른 올바른 구조체 다음 구조체 자료형 선언에 따른 올바른 구조체 변수 선언 방법은변수 선언 방법은 ??

struct ken {struct ken { int kkk;int kkk; float bbb;float bbb; };}; 1) struct ken yoo, soo;1) struct ken yoo, soo; 2) yoo, soo ken;2) yoo, soo ken; 3) ken yoo, soo;3) ken yoo, soo; 4) struct yoo, soo;4) struct yoo, soo;

Page 65: 구조체 (Structures )

2. 2. 다음 구조체 선언에 대해 멤버 값을 올바르게 입력하는 것은다음 구조체 선언에 대해 멤버 값을 올바르게 입력하는 것은 ?? struct ken {struct ken { int hakbun;int hakbun; int gwa;int gwa; int college;int college; } daehak;} daehak; 1) scanf(“%d”,&daehak->gwa); 1) scanf(“%d”,&daehak->gwa); 2) scanf(“%d”,&daehak.gwa);2) scanf(“%d”,&daehak.gwa); 3) scanf(“%d”,*daehak.gwa); 4) scanf(“%d”,daehak.gwa);3) scanf(“%d”,*daehak.gwa); 4) scanf(“%d”,daehak.gwa);

3. 3. 다음 구조체 선언에서 구조체 변수 다음 구조체 선언에서 구조체 변수 kenken 의 초기값 의 초기값 44.444.4 를 를 가리키는 것은가리키는 것은 ??

struct jemok {struct jemok { int hakbun;int hakbun; char gwa;char gwa; float ccc;float ccc; };}; struct jemok ken[]={8001,’a’,33.3,8002,’b’,44.4,struct jemok ken[]={8001,’a’,33.3,8002,’b’,44.4, 8003,’c’,55.5};8003,’c’,55.5};

Page 66: 구조체 (Structures )

1) ken[1]->ccc1) ken[1]->ccc 2) ken[1].ccc2) ken[1].ccc3) ken->ccc[1]3) ken->ccc[1] 4) ken.ccc[1]4) ken.ccc[1]

4. 4. 구조체의 초기화 형식으로 옳게 표현한 것은구조체의 초기화 형식으로 옳게 표현한 것은 ? (? (괄호 안괄호 안 )) structstruct pyo { pyo { int no;int no; char name[10];char name[10]; } (…)} (…)1) a={25,1) a={25, 안중근안중근 };}; 2) a=(25,”2) a=(25,” 안중근”안중근” ););3) a:=(“25”,”3) a:=(“25”,” 안중근”안중근” );); 4) a={25,”4) a={25,” 안중근”안중근” };};

5. 5. 다음 구조체 포인터의 멤버 참조 표현으로 올바른 것은다음 구조체 포인터의 멤버 참조 표현으로 올바른 것은 ?? struct man {struct man { char *name;char *name; int age;int age; } *student;} *student;

Page 67: 구조체 (Structures )

1) name->student1) name->student 2) age->student2) age->student3) student->name3) student->name 4) student.age4) student.age

6. 6. 다음 설명 중 올바른 것은다음 설명 중 올바른 것은 ??1) 1) 구조체의 구성 멤버는 반드시 같은 형구조체의 구성 멤버는 반드시 같은 형 (type)(type) 이어야 한다이어야 한다 ..2) 2) 구조체 구성 멤버의 접근은 배열과 같이 첨자구조체 구성 멤버의 접근은 배열과 같이 첨자 (index)(index) 를 를

사용한다사용한다 ..3) 3) 구조체 선언시 구조체명 없이 선언할 수 없다구조체 선언시 구조체명 없이 선언할 수 없다 ..4) 4) 구조체 내의 멤버로 또 다른 구조체를 가질 수 있다구조체 내의 멤버로 또 다른 구조체를 가질 수 있다 ..