1 / 30

10 장 데이터 구조체로서의 레코더

10 장 데이터 구조체로서의 레코더. 창원대학교 정보통신공학과 박동규. 10.1 단순구조체. 구조체란 ? 개개의 요소들을 관련있는 유니트로 결합하고 유니트를 구성하고 있는 자료 항목들 사이 통신방법을 정의한다 . 레코드는 간단한 형태의 구조체이다 . 예를들어 학생이 영어 국어 수학 과목을 수강할 경우 이 학생의 경우 영어 , 국어 , 수학 , 총합 , 학번 , 이름 항목이 서로 연관성 있는 단위가 될 수 있다 . 예를들어 회사의 사원에 대한 레코드를 만들 경우

Download Presentation

10 장 데이터 구조체로서의 레코더

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 10장 데이터 구조체로서의 레코더 창원대학교 정보통신공학과 박동규

  2. 10.1 단순구조체 • 구조체란? • 개개의 요소들을 관련있는 유니트로 결합하고 유니트를 구성하고 있는 자료 항목들 사이 통신방법을 정의한다. 레코드는 간단한 형태의 구조체이다. • 예를들어 학생이 영어 국어 수학 과목을 수강할 경우 이 학생의 경우 • 영어, 국어, 수학, 총합, 학번, 이름 항목이 서로 연관성 있는 단위가 될 수 있다. • 예를들어 회사의 사원에 대한 레코드를 만들 경우 • 사원번호, 사원이름, 사원급료 등이 서로 연관성 있는 단위가 될 수 있다 • 날짜의 경우 년, 월, 일이 구조체가 될 수 있다

  3. 구조체의 예 • e-mail의 헤더파일을 살펴보면 e-mail이 전형적인 구조체의 형태임을 알 수 있다 Received: from n-top.com ([203.226.253.216]) by sarim.changwon.ac.kr (8.11.6+Sun/8.11.6) with ESMTP id h4G5qme08698 for <dgpark@sarim.changwon.ac.kr>; Fri, 16 May 2003 14:52:48 +0900 (KST) Received: from nate (127.0.0.1) by n-top.com (6.5.033) id 3EB92EE80029FB44 for dgpark@sarim.changwon.ac.kr; Fri, 16 May 2003 14:51:04 +0900 Message-ID: <3EB92EE80029FB44@mailweb11.n-top.com> (added by postmaster@n-top.com) MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="=_9c96508cd8a39437fe06511ed3159629" From: "=?euc-kr?B?Y22y/z32UP++8KD/O2ag?="<parangy@lycos.co.kr> To: dgpark@sarim.changwon.ac.kr Subject: =?euc-kr?B?yLjAx7fP?= Date: Fri, 16 May 2003 14:51:04 +0900 Content-Length: 16017 Status: RO --=_9c96508cd8a39437fe06511ed3159629 Content-Type: text/html; charset="euc-kr" Content-Transfer-Encoding: base64 PElNRyBTUkM9ICJodHRwOi8vbWFpbC5uYXRlLmNvbS9OYXRlQ29uZmlybU1nci5waHA/YWN0PWNv bmZpcm0ma2V5PTEwNTMwNjQyNjRfZGdwYXJrQHNhcmltLmNoYW5nd29uLmFjLmtyJmZyb209fCEh ITI0fDcwMHwwOHxwYXJhbmd5QGx5Y29zLmNvLmtyIiBoZWlnaHQ9IjAiIHdpZHRoPSIwIj48SFRN

  4. 구조체의 선언 • 구조체의 선언: 월, 일 , 년으로 구성된 생일을 표현하기 위한 구조체를 예를 들면 아래와 같이 정의 struct { int month; int day; int year; } birth; 구조체의 멤버

  5. 구조체의 참조 • 구조체의 참조방법: (구조체 이름).(항목이름) 예) birth.month • 프로그램 예 #include <iostream.h> #include <string.h> viod main(void) { struct { char name[20]; int year; float salary; } employee; strcpy(employee.name, “Gildong Hong”); employee.year = 33; employee.salary = 23500.00; cout << “Employee ”<< employee.name << endl ; }

  6. 연습 • 프로그램 10-2를 입력하여 그 수행결과를 확인하시오

  7. 구조체형(structure type)의 선언 struct Date { int month; int day; int year; }; • structure type이 선언되면 int와 같은 자료형처럼 사용된다. 예) Date birth, current;

  8. 구조체의 초기화 • 구조체는 다음과 같이 초기화 할 수 있다 Date birth = { 12, 28, 72}; struct { char name[20]; int year; float salary; } employee = { “Gildong Hong”, 33, 2350000};

  9. 과제 • 연습문제 10.1의 • 1번 : 각각의 레코드에 대한 구조체 생성 • 2번 : 1번의 구조체를 이용하여 구조체를 초기화 한 후 그 값을 출력

  10. 10.2 구조체 배열 • 고용자가 10명인 회사에서는 구조체를 배열로 선언할 수 있으며, 이 경우 편리하게 데이터 처리가 가능 • 구조체 배열의 선언방법: struct Pay_rec{ int idnum; char name[20]; float rate; }; Pay_rec employee[10]; • 또는 struct { int idnum; char name[20]; float rate; } employee[10];

  11. 구조체 배열의 사용 • 구조체 배열의 사용방법 employee[4].name = “Gildong Hong” pay = employee[4].rate*hours; • 여기서 employee[4]는 5번째 레코드를 나타낸다. • 구조체 배열의 초기화 Pay_rec employee[3]={ {1234, “홍길동”, 3.25}, { 3456, “홍길순”, 4.54}, {5432, “이순신”, 5.55} }; for (j=0; j<3; j++) cout<< employee[j].idnum << ‘ ‘ << employee[j].name << ‘ ‘ << employee[j].rate;

  12. 연습 • 프로그램 10-3을 입력하여 그 결과를 확인하여라

  13. 과제 • 연습문제 10.2의 2번 문제를 구조체를 이용하여 해결하여라. • 각각의 값을 출력하여 입력이 제대로 되었는가를 확인하도록 하여라

  14. 10.3 구조체의 전달과 리턴 • 구조체는 스칼라 변수처럼 pass by value (값에 의한 전달) 또는 call by value (값에 의한 호출) 로 전달된다. • 예) display(birth.moth); // 구조체 멤버의 값을 복사해서 전달 • displayAll(birth); // 구조체 전체를 복사해서 전달

  15. 사용 예- 프로그램 10-4 #include <iostream.h> #include <iomanip.h> struct Employee { int id_num, double pay_rate; double hours; }; double calc_net(Employee); // 함수 prototype void main(void) { Employee emp = {6782, 8.0, 40.0}; double net_pay; net_pay = calc_net(emp);

  16. cout << “The net pay for employee” << emp.id_num << “is $ ” << setiosflags(ios::showpoint) << setiosflags(ios::left) << setw(10) << setprecision(2) << net_pay; } double calc_net(Employee temp) { // main의 temp와 temp는 같은 메모리가 아니다. return ( temp.pay_rate * temp.hours ); } ** 수행결과는?

  17. 연습 • 프로그램 10-4a를 입력하여 그 결과를 확인하시오 • 프로그램 10-4a는 call by reference에 의한 함수 호출을 채택하고 있다.

  18. 포인터의 사용 • 포인터의 전달 • 메모리 공간 절약. 그러나 의도하지 않은 자료변경이 가능하기 때문에 사용시 주의가 필요하다. • 사용 예: #include <iostream.h> #include <iomanip.h> struct Employee //구조체 선언 { int id_num; double pay_rate; double hours; }; double calc_net(Employee *);

  19. void main(void) { Employee emp = {6782, 8.93, 40.5}; double net_pay; net_pay = calc_net(&emp); cout << “The net pay for employee” << emp.id_num << “is $ ” << setiosflag(ios::showpoint) << setiosflags(ios::left) << setw(10) << net_pay << endl; }

  20. double calc_net(Employee *pt) { //pt->id_num = 1000; return((*pt).pay_rate * (*pt).hours); } • pt->id_num 은 (*pt).id_num과 동일 • 함수내에서 pt->id_num 이 바뀌었으며 이 값을 함수의 바깥에서도 유효함

  21. 증가 연산자 • ++pt->hours 연산의 결과는 • ++(pt->hours) 와 동일함 • 즉 pt 구조체의 hours 멤버를 읽어서 이 값에 1을 더해주는 역할을 한다 • (++pt)->hours 의 의미

  22. 포인터를 이용한 구조체의 전달 • 위 예에서 emp와 pt 는 다음과 같이 사상된다. *pt 는 구조체의 제일 앞인 id_num의 멤버를 갖는다. . (*pt).hours는 구조체 내에서 hours 멤버를 갖는다.

  23. 구조체의 반환 • 반환하는 함수 선언에서는 함수 type을 구조체형으로 선언하고 return(name)을 실행 예) Employee get_vals(void) { Employee next; next.id_num=6783; next.pay_rate = 16.25; next.hours = 38.0; return(next); }

  24. 10.4 연결 리스트 • 배열 이용 • 미리 큰 공간을 확보. 따라서 메모리 낭비. • 특정 레코드의 추가/삭제시 이후의 모든 레코드를 한 칸씩 아래/위로 이동 • 데이터의 추가와 삭제가 빈번히 일어날 경우 매우 비효율적 • 연결 리스트 사용 • 미리 큰 메모리 영역을 확보할 필요가 없다. • 레코드의 추가/삭제시에 전체 리스트를 재정렬이 불필요. • 프로그래밍 비용이 증가함

  25. 예: 새로운 Dongsu 레코드를 삽입 • 처음 상태 새로운 레코드가 삽입되어 재정렬된 경우

  26. 예제 : 프로그램 10-8 #include <iostream.h> struct Tele_type { char name[30]; char phone_no[15]; Tele_type *nextaddr; }; void main(void) { Tele_type t1={“Acme, Sam”, “(201) 898-2392”}; Tele_type t2={“Dolan, Edith”, “(213) 682-3104”}; Tele_type t3={“Lanfrank, John”, “(415) 718-4581”}; Tele_type *first; first = &t1; t1.nextaddr=&t2; t2.nextaddr = &t3; t3.nextaddr=NULL; while (first!=NULL) { cout << ‘\n’ << first->name; first = first->nextaddr; } }

  27. 연습 • 프로그램 10-9를 입력하여 그 결과를 확인하시오 #include <iostream.h> #include <iomanip.h> struct Tele_typ { char name[30]; char phone_no[15]; Tele_typ *nextaddr; }; void display (Tele_typ *); void main(void) { Tele_typ t1 = {"Acme, Sam", "(201) 898-2392"}; Tele_typ t2 = {"Dolan, Edith", "(221) 857-2872"}; Tele_typ t3 = {"Lanfrank, John", "(343) 654-4241"}; Tele_typ *first;

  28. first = &t1; t1.nextaddr = &t2; t2.nextaddr = &t3; t3.nextaddr = NULL; display(first); } void display (Tele_typ *contents) { while (contents != NULL) { cout << endl << setiosflags(ios::left) << setw(30) << contents->name << setw(20) << contents->phone_no; contents = contents->nextaddr; } cout << endl; return; }

  29. 10.5 동적 구조체 할당 • new : 메모리 영역을 할당. 예약된 공간의 시작주소를 return하고 공간이 충분하지 않을 경우 NULL을 return. • delete : 이전에 예약되었던 공간을 삭제

  30. 연습 • 프로그램 10-10을 입력하여 그 결과를 확인하시오 • cin >> key ; • 프로그램 10-11을 입력하여 그 결과를 확인하시오

More Related