Upload
joshua-hernandez
View
54
Download
0
Embed Size (px)
DESCRIPTION
10 장 데이터 구조체로서의 레코더. 창원대학교 정보통신공학과 박동규. 10.1 단순구조체. 구조체란 ? 개개의 요소들을 관련있는 유니트로 결합하고 유니트를 구성하고 있는 자료 항목들 사이 통신방법을 정의한다 . 레코드는 간단한 형태의 구조체이다 . 예를들어 학생이 영어 국어 수학 과목을 수강할 경우 이 학생의 경우 영어 , 국어 , 수학 , 총합 , 학번 , 이름 항목이 서로 연관성 있는 단위가 될 수 있다 . 예를들어 회사의 사원에 대한 레코드를 만들 경우 - PowerPoint PPT Presentation
Citation preview
10 장 데이터 구조체로서의 레코더
창원대학교 정보통신공학과
박동규
10.1 단순구조체
구조체란 ? 개개의 요소들을 관련있는 유니트로 결합하고 유니트를
구성하고 있는 자료 항목들 사이 통신방법을 정의한다 . 레코드는 간단한 형태의 구조체이다 .
예를들어 학생이 영어 국어 수학 과목을 수강할 경우 이 학생의 경우
영어 , 국어 , 수학 , 총합 , 학번 , 이름 항목이 서로 연관성 있는 단위가 될 수 있다 .
예를들어 회사의 사원에 대한 레코드를 만들 경우 사원번호 , 사원이름 , 사원급료 등이 서로 연관성 있는
단위가 될 수 있다 날짜의 경우 년 , 월 , 일이 구조체가 될 수 있다
구조체의 예
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 h4G5qme08698for <[email protected]>; 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 [email protected]; Fri, 16 May 2003 14:51:04 +0900Message-ID: <[email protected]> (added by [email protected])MIME-Version: 1.0Content-Type: multipart/mixed;
boundary="=_9c96508cd8a39437fe06511ed3159629"From: "=?euc-kr?B?Y22y/z32UP++8KD/O2ag?="<[email protected]>To: [email protected]: =?euc-kr?B?yLjAx7fP?=Date: Fri, 16 May 2003 14:51:04 +0900Content-Length: 16017Status: RO
--=_9c96508cd8a39437fe06511ed3159629Content-Type: text/html; charset="euc-kr"Content-Transfer-Encoding: base64
PElNRyBTUkM9ICJodHRwOi8vbWFpbC5uYXRlLmNvbS9OYXRlQ29uZmlybU1nci5waHA/YWN0PWNvbmZpcm0ma2V5PTEwNTMwNjQyNjRfZGdwYXJrQHNhcmltLmNoYW5nd29uLmFjLmtyJmZyb209fCEhITI0fDcwMHwwOHxwYXJhbmd5QGx5Y29zLmNvLmtyIiBoZWlnaHQ9IjAiIHdpZHRoPSIwIj48SFRN
구조체의 선언
구조체의 선언 : 월 , 일 , 년으로 구성된 생일을 표현하기 위한 구조체를 예를 들면 아래와 같이 정의
struct{
int month; int day;
int year;} birth;
구조체의 멤버
구조체의 참조 구조체의 참조방법 : ( 구조체 이름 ).( 항목이름 )예 ) 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 ;
}
연습
프로그램 10-2 를 입력하여 그 수행결과를 확인하시오
구조체형 (structure type) 의 선언
struct Date{
int month;int day;int year;
};
structure type 이 선언되면 int 와 같은 자료형처럼 사용된다 .예 ) Date birth, current;
구조체의 초기화
구조체는 다음과 같이 초기화 할 수 있다Date birth = { 12, 28, 72};struct {
char name[20]; int year; float salary;
} employee = { “Gildong Hong”, 33, 2350000};
과제
연습문제 10.1 의 1 번 : 각각의 레코드에 대한 구조체 생성 2 번 : 1 번의 구조체를 이용하여 구조체를 초기화 한 후 그
값을 출력
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];
구조체 배열의 사용
구조체 배열의 사용방법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;
연습
프로그램 10-3 을 입력하여 그 결과를 확인하여라
과제
연습문제 10.2 의 2 번 문제를 구조체를 이용하여 해결하여라 . 각각의 값을 출력하여 입력이 제대로 되었는가를
확인하도록 하여라
10.3 구조체의 전달과 리턴
구조체는 스칼라 변수처럼 pass by value ( 값에 의한 전달 ) 또는 call by value ( 값에 의한 호출 ) 로 전달된다 . 예 ) display(birth.moth); // 구조체 멤버의 값을
복사해서 전달 displayAll(birth); // 구조체 전체를 복사해서 전달
사용 예 - 프로그램 10-4#include <iostream.h>#include <iomanip.h>struct Employee{ int id_num, double pay_rate; double hours; };double calc_net(Employee);
// 함수 prototypevoid main(void){ Employee emp = {6782, 8.0, 40.0}; double net_pay; net_pay = calc_net(emp);
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 );}** 수행결과는 ?
연습
프로그램 10-4a 를 입력하여 그 결과를 확인하시오 프로그램 10-4a 는 call by reference 에 의한 함수
호출을 채택하고 있다 .
포인터의 사용
포인터의 전달 메모리 공간 절약 . 그러나 의도하지 않은 자료변경이
가능하기 때문에 사용시 주의가 필요하다 . 사용 예 :#include <iostream.h>#include <iomanip.h>struct Employee // 구조체 선언{int id_num;double pay_rate;double hours;};double calc_net(Employee *);
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;}
double calc_net(Employee *pt){//pt->id_num = 1000;return((*pt).pay_rate * (*pt).hours);} pt->id_num 은 (*pt).id_num 과 동일 함수내에서 pt->id_num 이 바뀌었으며 이 값을 함수의
바깥에서도 유효함
증가 연산자
++pt->hours 연산의 결과는 ++(pt->hours) 와 동일함 즉 pt 구조체의 hours 멤버를 읽어서 이 값에 1 을
더해주는 역할을 한다 (++pt)->hours 의 의미
포인터를 이용한 구조체의 전달
위 예에서 emp 와 pt 는 다음과 같이 사상된다 .
emp의시작주소
(*pt).hours
(*pt).pay_rate
(*pt).id_num = *pt
emp:
id_num pay_rate hours
*pt 는 구조체의 제일 앞인 id_num 의 멤버를 갖는다 .. (*pt).hours 는 구조체 내에서 hours 멤버를 갖는다 .
구조체의 반환
반환하는 함수 선언에서는 함수 type 을 구조체형으로 선언하고 return(name) 을 실행
예 )Employee get_vals(void){ Employee next;
next.id_num=6783;next.pay_rate = 16.25;next.hours = 38.0;
return(next);}
10.4 연결 리스트
배열 이용 미리 큰 공간을 확보 . 따라서 메모리 낭비 . 특정 레코드의 추가 /삭제시 이후의 모든 레코드를 한 칸씩
아래 /위로 이동 데이터의 추가와 삭제가 빈번히 일어날 경우 매우 비효율적
연결 리스트 사용 미리 큰 메모리 영역을 확보할 필요가 없다 . 레코드의 추가 /삭제시에 전체 리스트를 재정렬이 불필요 . 프로그래밍 비용이 증가함
처음 상태
Gildong
(02)682-0001
Address of Chulsu
Chulsu
(0331)202-0001
Address of Next
Gildong
(02)682-0001
Address of Dongsu
Chulsu
(0331)202-0001
Address of Next
Dongsu
(02)702-0001
Address of Chulsu
새로운 레코드가 삽입되어 재정렬된 경우
예 : 새로운 Dongsu 레코드를 삽입
예제 : 프로그램 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;}
}
연습 프로그램 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;
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;
}
10.5 동적 구조체 할당
new : 메모리 영역을 할당 . 예약된 공간의 시작주소를 return 하고 공간이 충분하지 않을 경우 NULL 을 return.
delete : 이전에 예약되었던 공간을 삭제
연습
프로그램 10-10 을 입력하여 그 결과를 확인하시오
cin >> key ;
프로그램 10-11 을 입력하여 그 결과를 확인하시오