Presentation is loading. Please wait.

Presentation is loading. Please wait.

Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 서울대학교 기계항공공학부 담당 : 김 찬 중 컴퓨터 개론 및 실습 강의 8 2013. 04. 02.

Similar presentations


Presentation on theme: "Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 서울대학교 기계항공공학부 담당 : 김 찬 중 컴퓨터 개론 및 실습 강의 8 2013. 04. 02."— Presentation transcript:

1 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 서울대학교 기계항공공학부 담당 : 김 찬 중 컴퓨터 개론 및 실습 강의 8 2013. 04. 02

2 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 2 구조체 (Structure) ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

3 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 3 구조체 (structure) ■ 구조체가 필요한 이유 평면 위의 점 P(a,b) 는 x 축 좌표 a 와 y 축 좌표 b 를 가지는 구조이다. 이와 같이 하나의 데이터 형이 여러 개의 독립적인 원소를 가진 구조를 효과적으로 처리하기 위해서 C 언어에서는 구조체를 사용한다. P(a,b) x y

4 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 4 구조체의 정의 ■ 구조체의 정의 평면 위의 점 P(a,b) 는 x 축 좌표 a 와 y 축 좌표 b 를 가지는 구조를 표현하기 위해서 struct point { // struct 은 C 언어의 키워드 (keyword) 이다. double x; // x-coordinate double y; // y-coordinate }; 으로 point 의 구조를 정의한다. 위와 같이, 구조체의 형식만 정의하는 경우에는 {} 의 마지막이 세미콜론으로 끝나는 점에 주의해야 한다. 구조체의 형식 {} 내부에 정의되는 것을 멤버 (member) 라고 하고, 구조체의 이름을 tag 라고 한다. tag member structure tag

5 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 5 구조체 (structure)의 예 ■ 구조체의 몇 가지 예 앞에서 고려한 구조체 point 처럼 여러 가지의 구조체를 활용할 수 있다. struct point { // 평면 위의 점을 처리하기 위한 구조체 double x; // x-coordinate double y; // y-coordinate }; struct person { // 인사기록을 관리하기 위한 구조체 char name[30]; // identification char sex; // male or female int age; // age }; struct complex { // 복소수를 처리하기 위한 구조체 double x; // real double y; // imaginary };

6 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 6 구조체 의 객체(object) ■ 객체 (object) 또는 구조체 변수 (structure variable) 의 선언 앞에서 정의한 구조체 point 의 구조를 가지는 객체 ( 그림의 점 P,Q,R) 의 선언은 struct point P = {3,1}, Q = {1,2}, R; 의 형태로 구조체 이름(tag) 다음에 객체 이름과 초기값을 지정한다. 중괄호 {}로 묶는 초기화를 하지 않는 경우에는 이름만 지정한다. 이것은 int p = 3, q = 2, r ; 으로 정수 p,q,r 을 선언할 때와 거의 유사하다. 위에서 보듯이, “struct point”는 “int”와 같이 하나의 데이터 형으로 취급하면 된다. P(3,1) Q(1,2) R(4,3) x y x,y

7 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 7 구조체의 연산 (Operations on Structure) ■ 멤버에의 접근 구조체의 멤버는 도트 (.) 다음에 멤버 이름을 붙여 read/write 할 수 있다. struct point P,Q,R; 으로 초기값을 설정하지 않은 객체에 대해서 P.x = 3; P.y = 1; Q.x = 1; Q.y = 2; 으로 각 점의 멤버값을 설정할 수 있다. P(3,1) Q(1,2) R(4,3) x y struct point { double x; // x-coordinate double y; // y-coordinate };

8 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 8 구조체의 연산 (Operations on Structure) ■ 구조체의 포인터 구조체를 가리키는 포인터는 prefix * 를 앞에 붙여서 정의하고, 구조체의 객체를 저장하는 기억장소의 주소는 prefix & 를 붙여 얻는다. struct point P,Q,R, *iP = &P,*iQ = &Q; 포인터에 의한 멤버의 접근은 포인터 다음에 postfix -> (minus, greater than)을 붙여서 이용할 수 있다. 즉 iP 는 P 의 포인터이므로 ( iP = &P ) (*iP).x iP->x P.x 는 모두 동일하며, read/write 가능하다. 위에서, 도트 (.) 는 가장 우선순위가 높은 연산자이므로 (*iP) 와 같이 괄호가 필요하다. P(3,1) Q(1,2) R(4,3) x y

9 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 9 구조체의 연산 (Operations on Structure) ■ 구조체의 복사 구조체의 객체는 자신 만의 기억장소를 가지는 데이터이며, 복사는 대응하는 각 멤버별로 이루어진다. struct point P = {3,1}, Q ={1,2}; Q = P; 위에서 Q = P; 는 다음의 두 명령과 동일하다. Q.x = P.x; Q.y = P.y; ■ 문자열 복사와의 차이 char p[] = “abc”, q[] = “xyz”; 에서 p = q; 인 명령은 포인터의 주소를 옮기는 것이므로, 복사를 하려면 strcpy(p,q); 을 실행해야하는 점이 정수, 구조체의 복사와 다른 점이다.

10 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 10 구조체와 함수 함수를 이용하여 구조체 point 의 멤버를 바꿀 수 있다. struct point makepoint(double x,double y) { struct point tmp; tmp.x = x; tmp.y = y; return tmp; } P = makepoint(3,1); Q = makepoint(1,2); 함수 makepoint 의 매개변수 x,y 와 구조체의 멤버 x,y 는 전혀 별개의 변수이다. 구조체의 멤버는.x 또는 ->x 에 의해서만 접근할 수 있으므로, 영문자로 시작하는 일반변수 x 와 서로 구별할 수 있는 것은 당연한다. P(3,1) Q(1,2) R(4,3) x y

11 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 11 구조체와 함수 구조체 point 를 함수의 매개변수로 사용할 수 있다. 아래의 그림처럼 평행사변형의 법칙을 이용하여 두 벡터의 합을 구하는 함수를 정의한다. struct point addpoint(struct point A, struct point B) { A.x += B.x; A.y += B.y; return A; } R = addpoint(P,Q); 함수 addpoint 는 구조체를 매개변수로 받고, 구조체를 리턴해준다. P(3,1) Q(1,2) R(4,3) x y

12 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 12 형 정의 (typedef) ■ 형 정의 (typedef) 구조체 point 의 객체를 선언하기 위해서 사용되는 “struct point”는 “int”와 같이 하나의 데이터 형으로 취급할 수 있으므로, 형 정의(typedef)를 이용하여 새로운 데이터 형을 정의할 수 있다. typedef struct point Point; // 새로운 데이터 형 Point 를 정의 Point P,Q,R; 은 struct point P,Q,R; 과 동일하다. 그리고 앞에서 사용한 함수 선언을 struct point addpoint(struct point A, struct point B); Point addpoint(Point A, Point B); 으로 다시 써서 프로그램을 간단히 할 수 있다. 이것은 마치 #define 을 아래와 같이 사용한 것과 유사하다. // #define Point struct point

13 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 13 구조체의 응용예 ■ 복소수 연산을 위한 구조체 typedef struct Complex cplx; struct Complex { double x; double y; }; cplx make(double x,double y) { cplx z = {x,y}; return z; } cplx mul(cplx u, cplx v) { return make(u.x*v.x-u.y*v.y, u.x*v.y+u.y*v.x ); } cplx div(cplx u, cplx v) { double d = 1./(v.x*v.x+v.y*v.y +1.e-60); // to avoid division-by-zero return make( (u.x*v.x+u.y*v.y)*d, (-u.x*v.y+u.y*v.x)*d ); } cplx u,v,z; u = make(1,2); v = make(3,4); z = mul(u,v); printf("%g %g\n", z.x, z.y); z = div(u,v); printf("%g %g\n", z.x, z.y); -5 10 0.44 0.08

14 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 14 sizeof ■ sizeof 데이터의 크기를 구하는 것은 sizeof 를 sizeof (data_type) sizeof (variable) 으로 사용한다. sizeof(int); int n; sizeof(n); 위의 두 가지 표현은 모두 정수형 데이터의 크기 4 를 나타낸다. 앞에서 정의한 구조체 point 의 경우 sizeof(struct point) 는 두 개의 실수형을 멤버로 가지므로 16 을 리턴한다. sizeof(char) // 1 sizeof(int) // 4 sizeof(long) // 4 sizeof(float) // 4 sizeof(double) // 8

15 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 15 구조체의 구조체 구조체의 구조체도 아주 유용하다. 예를 들어, 사각형을 표현하기 위해서 대각선으로 마주 보는 2 개의 점을 지정할 수 있다. 이 경우, struct point { double x; double y; }; struct rect { struct point pt1; struct point pt2; }; 으로 쓸 수 있다. 사각형의 한 점 pt1 의 좌표가 (3,2) 이면 struct rect box; box.pt1.x = 3; box.pt1.y = 2; 와 같이 좌표값에 접근할 수 있다.

16 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 16 구조체의 배열 삼각형을 이루는 3 개의 점을 나타내기 위해서는 3 개의 point 객체가 필요하고, 이것을 배열로 다음과 같이 선언할 수 있다. struct point ABC[3] = { 0,0, 3,0, 1,2 }; 멤버의 갯수가 2 개임으로 알기 때문에 순서대로 2 개 씩 구조체를 초기화한다. 그러나, 보다 명확히 하기 위해서 각 구조체의 초기화를 {} 으로 묶을 수 있다. 이때, 각 {} 에서 생략된 멤버값은 바로 앞의 값으로 초기화된다. struct point PQR[3] = { {0}, {3,0}, {1,2} };

17 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 17 유니온 (union) 어떤 상품을 진열하는데 가격 또는 메이커 중에서 한 가지만 표시하면 되는 경우에 구조체를 struct item { int price; char maker[10]; }; 으로 선언하게 되면 기억장소를 낭비하게 된다. 왜냐하면 price, maker 중에 하나만 사용하기 때문이다. 이러한 경우, 두 가지 데이터형을 하나의 공통된 기억장소에 저장하고 각각 다른 이름으로 호출할 수 있다. struct item { int utype; // save which type is used union { int price; // type is int char maker[10]; // type is char };

18 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 18 유니온 (union) struct item { int utype; // save which type is used union { int price; // type is int char maker[10]; // type is char }; struct item A; ■ 유니온은 구조체와 동일한 형식으로 선언된다. ■ 유니온의 모든 멤버는 기억장소가 같다. 즉, &A.price와 &A.maker 는 동일하다. ■ 유니온의 기억장소의 크기는 멤버 중에서 가장 큰 기억장소를 가지는 멤버로 결정된다. ■ 유니온의 가장 처음 나오는 멤버의 형으로 초기화된다. 위의 경우 int price 가 첫 번째 멤버이므로 정수로 초기화 된다.

19 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 19 union 의 응용예 ■ 유니온의 사용예 struct item A; A.utype = 1; A.price = 120; if (A.utype == 1 ) printf("%d \n", A.price ); else if(A.utype == 2 ) printf("%s \n", A.maker ); A.utype = 2; strcpy(A.maker,"company"); if (A.utype == 1 ) printf("%d \n", A.price ); else if(A.utype == 2 ) printf("%s \n", A.maker ); printf(“No way !!! %d \n", A.price ); ■ 결과 120 company No way !!! 1886220131

20 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 20 구조체의 상대참조 ■ 두 개의 구조체가 상대를 각각 참조하는 경우 struct t {... struct s *p; // p points to an s }; struct s {... struct t *q; // q points to a t }; 위에서 구조체 t 를 정의할 때 구조체 s 는 아직 정의되어 있지 않다. 따라서, 닭이 먼저냐, 계란이 먼저냐의 문제처럼 두 개의 구조체가 서로를 참조할 때는 어느 한 쪽은 반드시 정의되지 않은 상태이므로, 포인터로 참조해야만 한다 ( 포인터는 sizeof 값이 일정하게 정해져 있기 때문이다 ). ??? 아래에서 정의될 것임 포인터의 크기 (sizeof) 는 정해져 있으므로 struct s 의 정의를 몰라도 된다

21 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 21 구조체의 자기참조 ■ 이진트리 어떠한 입력에서 발생할 수 있는 모든 단어의 발생횟수를 세는 문제를 다음과 같이 이진트리(binary tree)라고 불리는 자기참조 구조체를 이용하여 해결할 수 있다. 트리는 서로 다른 각 단어마다 하나의 마디(node)를 갖는데 각 마디는 다음과 같은 정보를 가진다. 단어에 대한 포인터 (a pointer to the text of the word) 발견된 횟수 (a count of the number of occurrence) 왼쪽 가지에 대한 포인터 (a pointer to the left child node) 오른쪽 가지에 대한 포인터 (a pointer to the right child node) 어떠 마디도 두 개 이상의 가지를 가질 수 없으며, 가지의 번호는 0과 1로 표현된다. 각 마디의 왼쪽 가지에는 그 마디보다 작은 값을 갖는 마디만 있고, 오른쪽 가지에는 그 마디의 가지보다 큰 값을 갖는 마디만 오게 된다.

22 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 22 구조체의 자기참조 ■ 이진트리의 예 아래의 입력으로 단어의 발생횟수를 세는 이진트리를 만들어 보자. “now is the time for all good men to come to the aid of their party” now is ☞

23 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 23 구조체의 자기참조 ■ 이진트리의 예 아래의 입력으로 단어의 발생횟수를 세는 이진트리를 만들어 보자. “now is the time for all good men to come to the aid of their party” now isthe ☞

24 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 24 구조체의 자기참조 ■ 이진트리의 예 아래의 입력으로 단어의 발생횟수를 세는 이진트리를 만들어 보자. “now is the time for all good men to come to the aid of their party” now isthe ☞ time

25 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 25 구조체의 자기참조 ■ 이진트리의 예 아래의 입력으로 단어의 발생횟수를 세는 이진트리를 만들어 보자. “now is the time for all good men to come to the aid of their party” now is for the ☞ time

26 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 26 구조체의 자기참조 ■ 이진트리의 예 아래의 입력으로 단어의 발생횟수를 세는 이진트리를 만들어 보자. “now is the time for all good men to come to the aid of their party” now is for all the ☞ time

27 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 27 구조체의 자기참조 ■ 이진트리의 예 아래의 입력으로 단어의 발생횟수를 세는 이진트리를 만들어 보자. “now is the time for all good men to come to the aid of their party” now is for all the good ☞ time

28 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 28 구조체의 자기참조 ■ 이진트리의 예 아래의 입력으로 단어의 발생횟수를 세는 이진트리를 만들어 보자. “now is the time for all good men to come to the aid of their party” now is for all the men good ☞ time

29 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 29 구조체의 자기참조 ■ 이진트리의 예 아래의 입력으로 단어의 발생횟수를 세는 이진트리를 만들어 보자. “now is the time for all good men to come to the aid of their party” now is for all the men good ☞ time to

30 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 30 구조체의 자기참조 ■ 이진트리의 예 아래의 입력으로 단어의 발생횟수를 세는 이진트리를 만들어 보자. “now is the time for all good men to come to the aid of their party” now is for all come the men good ☞ time to

31 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 31 구조체의 자기참조 ■ 이진트리의 예 아래의 입력으로 단어의 발생횟수를 세는 이진트리를 만들어 보자. “now is the time for all good men to come to the aid of their party” now is for all come the men good ☞ count 2 time to

32 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 32 구조체의 자기참조 ■ 이진트리의 예 아래의 입력으로 단어의 발생횟수를 세는 이진트리를 만들어 보자. “now is the time for all good men to come to the aid of their party” now is for all come the men good ☞ count 2 time to

33 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 33 구조체의 자기참조 ■ 이진트리의 예 아래의 입력으로 단어의 발생횟수를 세는 이진트리를 만들어 보자. “now is the time for all good men to come to the aid of their party” now is for all aidcome the men good ☞ the time to

34 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 34 구조체의 자기참조 ■ 이진트리의 예 아래의 입력으로 단어의 발생횟수를 세는 이진트리를 만들어 보자. “now is the time for all good men to come to the aid of their party” now is for all aidcome the men good ☞ the oftime to

35 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 35 구조체의 자기참조 ■ 이진트리의 예 아래의 입력으로 단어의 발생횟수를 세는 이진트리를 만들어 보자. “now is the time for all good men to come to the aid of their party” now is for all aidcome men good ☞ the oftime their to

36 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 36 구조체의 자기참조 ■ 이진트리의 예 아래의 입력으로 단어의 발생횟수를 세는 이진트리를 만들어 보자. “now is the time for all good men to come to the aid of their party” now is for all aidcome the menoftime goodparty their to ☞

37 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 37 구조체의 자기참조 struct treenode { char *word; // point to the text int count; // number of occurrences struct treenode *left; // pointer for the left child struct treenode *right; // pointer for the right child }; 구조체가 자기 자신을 포함하는 것은 안되지만 자신을 가리키는 포인터를 포함하는 것은 가능하다. 이러한 탐색과정은 어떤 마디에 대해 일치하지 않으면 그 가지에 대해 똑같은 과정을 하게 되므로 순환 (recursive) 과정이 된다. 이것을 구현하는 것이 포인터에 의한 자기참조이다.

38 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 38 구조체의 자기참조 struct treenode *treealloc(void) // make a treenode { return (struct treenode *) malloc(sizeof(struct treenode)); // 다음 페이지 참조 } struct treenode *addtree (struct treenode *p, char *w) { int cond; if( p == NULL ) { // a new word has arrived p = treealloc(); // make a new node p->word = strdup(w); // string duplicate p->count = 1; p->left = p->right = NULL; } else if( (cond = strcmp(w, p->word)) == 0 ) p->count++; // repeat word else if( cond left = addtree(p->left,w); // less than into left subtree else p->right = addtree(p->right,w); // greater than into right subtree return p; }

39 Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 39 malloc, free ■ 동적 기억장소 할당( dynamic storage allocation) malloc 는 기억장소블록 (block of bytes) 을 할당하고 그곳을 가리키는 포인터를 리턴한다. 이때, 기억장소의 크기는 sizeof 를 이용하면 된다. free(p) 는 포인터 p 가 가리키는 동적기억장소 블록을 해제 (release) 하여 다른 기억장소로 사용될 수 있도록 한다. 이때, free(p); p = NULL; 으로 포인터 p 가 더이상 아무 곳도 가리키지 않도록 마무리하는 것이 많은 경우 도움이 된다. struct treenode *treealloc(void) // make a treenode { return (struct treenode *) malloc(sizeof(struct treenode)); }


Download ppt "Computer Aided Thermal Design Laboratory www.msharpmath.com / 39 서울대학교 기계항공공학부 담당 : 김 찬 중 컴퓨터 개론 및 실습 강의 8 2013. 04. 02."

Similar presentations


Ads by Google