Upload
amber-wilcox
View
230
Download
0
Embed Size (px)
Citation preview
Chapter 12
Structure and ADTs
프로그래밍 기초와 실습
Chapter 12 Structure and ADTs 2
Contents
Declaring Structures
Accessing a Member
Operator Precedence and Associativity Structures, Functions, and Assignment
Problem Solving : Student Records
Initialization of Structures
The Use of typedef
Chapter 12 Structure and ADTs 3
Self-Referential Structures Linear Linked Lists Dynamic Allocation List Operations
Contents
Chapter 12 Structure and ADTs 4
Declaring Structures
Array 와 structure 의 차이점
– array
• Array 의 모든 element 는 같은 type 이여야 한다 .
• Index 를 사용하여 각 element 를 access 한다 .
– structure
• 다른 type 의 element 로 구성 될 수 있다 .
• 각 element 는 name 을 갖는다 .
• Name 에 의해 각 element 를 access 한다 .
Chapter 12 Structure and ADTs 5
Declaring Structures
struct declaration– Collection of members(/elements)
[Ex] struct { /* 3 elements 로 구성된 structure */ int number; char name [20] ; int on_hand;} part1;
{ } 의 형태로 variable ‘part1’ 을 선언한다 .Part1 은 int, char array, int type 의
3 member 를 포함하는 struct type 의 variable
Chapter 12 Structure and ADTs 6
Declaring Structures
structure tag
- 정의 되는 특정 structure 를 지정하기 위한 name.
- 한 번 structure tag 인 part 가 정의되면 , 이제 tag 를 사용하여 같은 structure type 으로 선언할 수 있다 .
[Ex] struct part { int number; char name [20] ; int on_hand;};
[Ex] struct part part1, part2 ; /* correct declaration */part part1, part2; /* wrong declaration */
struct tag:생략 가능하지만 생략 시
이 후에 선언 불 가능
Chapter 12 Structure and ADTs 7
Declaring Structures
structure tag 와 변수 동시 선언가능– structure tag 를 이용하여 선언된 변수는 같은 structure
type[Ex] struct part {
int number; char name [20] ; int on_hand;} part1, part2;
struct part part3;
part1, part2, part3 는 모두 compatible
Chapter 12 Structure and ADTs 8
Declaring Structures
Initializing Struct variables
[Ex] struct student { int number; char name [20] ; int score;
} part1 = {1, “handong”, 95}, part2;
part1
part1.number part1.name part1.score
1 handong 95
Chapter 12 Structure and ADTs 9
Declaring Structures
Compatible structure– 같은 type 의 structure variable 이면 서로 assign 가능
– compatible types 의 조건• Structure 정의와 동시에 선언되는 모든 variables
• 같은 type 의 structure 즉 같은 tag 에 의해 선언된 모든 variables.
[Ex] part1 = part2; /* legal operation */
part2 의 모든 member 의 values들은 part1 의 각 member 로 copy 된다 .
[Ex] struct part { int number; char name [20] ; int on_hand;
} part1, part2;
[Ex] struct part part3, part4;
/* part1, part2
part3, part4 모두 compatible
types */
Chapter 12 Structure and ADTs 10
Declaring Structures
Compatible structure
– compatible type 이 아닐 경우 =, ==, != 불가능
[Ex] struct { struct { int x, y; int x, y; } data1; } data2;
data1 = data2; /* illegal operation */
/* 같은 member 로 구성되어도 각 기 정의하여 선언 한다면 서로 다른 type 으로 not compatible */
Chapter 12 Structure and ADTs 11
Declaring Structures
[Ex] struct { int a[10];} a1, a2; a1 = a2; /* legal */
int a1[10], int a2[10]={0}; a1=a2; /* illegal*/
[Ex] struct {struct { int number;
char name[20]; int on_hand;
} part1;
struct { int number;
char name[20]; int on_hand; } part2 ;
part1 and part2 are notcompatible
Chapter 12 Structure and ADTs 12
Declaring Structures
[Ex] struct { int number; char name [20] ; int on_hand;
} part1;
Memory Allocation
– Structure 로 선언된 데이터 type 은 각 member 들이 메모리 내에 순차적으로 할당된다 .
– part1 의 base address 가 200 이고 , integer 의 size 가 4bytes 라고 가정하면 , 오른쪽 그림과 같이 메모리가 할당됨 .
200
204:
222
223
224
228
part1.number
part1.name[0]
part1.name[18]part1.name[19]part1.on_hand
Chapter 12 Structure and ADTs 13
Accessing a Member struct member operator ‘.’
– Structure 의 각 member 를 access 하기 위해 ‘ .’ 를 사용한다 .[Ex] struct {
int number; char name[20]; int on_hand; } part1={1, “Monitor”, 10};
printf (“Part number : %d\n”, part1.number);printf (“Part name : %s\n”, part1.name);printf (“Quantity on hand : %d\n”, part1.on_hand);
part1
part1.number part1.name part1.on_hand
1 Monitor 10
Part number : 1Part name : MonitorQuantity on hand : 10
Chapter 12 Structure and ADTs 14
Accessing a Member
member operation
[Ex] struct { int number; char name[20]; int on_hand; } part1;
scanf (“%d”, &part1.on_hand); /* reading using scanf() */scanf(“%s”, part1.name); part1.number = 258; /* assignment */part1.on_hand++; /* increment */
Chapter 12 Structure and ADTs 15
Accessing a Member
structure pointer
[Ex] struct complex { double re; double im;
};
struct complex c1, c2, *a=&c1, *b=&c2; /* a 는 structure ‘c1’ 을 refer, b 는 ‘ c2’ 을 refer*/
a->re = b->re + 2 ; /* c1.re = c2.re + 2; 와 동일 */ b->im = a->im – 3; /* c2.im = c1.im – 3; 와 동일 */
printf (“value ; %f\n ”, a->im);
Chapter 12 Structure and ADTs 16
Accessing a Member
[Ex] struct shape { int x, y ; char name[10] ;
};
struct shape s, *p = &s;scanf (“%d %d %s”, &p->x , &p->y, p->name ) ;
/* operator ‘->’ 는 ‘ &’ 를 우선한다 . &p->x &(p->x)*/
s.x = p->x * 2; /* p->x = s.x *2; 와 동일 */p->y = s.y % 5;
printf (“%d %d %s\n”, p->x , p->y, p->name ) ;
12 23 handong24 3 handong
Chapter 12 Structure and ADTs 17
Accessing a Member
[Ex] struct shape { int x, y ; char name[10] ;
};
struct shape s, *p = &s;scanf (“%d %d %s”, &(*p).x , &(*p).y, (*p).name ) ;
/* operator ‘.’ 는 ‘ &’ 를 우선한다 . &p->x &(*p).x*/
s.x = (*p).x * 2; /* p->x = s.x *2; 와 동일 */(*p).y = s.y % 5;
printf (“%d %d %s\n”, (*p).x , (*p). y, (*p). name ) ;
12 23 handong24 3 handong
괄호를 생략할경우 ‘ .’ 가 우선선위가 높으므로p.y 를 먼저 수행 . p 는 pointer 이므로 error 발생
Chapter 12 Structure and ADTs 18
Precedence and Associativity of Operators
( ) [ ] . -> ++(postfix) --(postfix) left to right
++(prefix) --(prefix) ! ~ sizeof(type)+(unary) -(unary) &(address) *(dereference)
right to left
* / % left to right
+ - left to right
<< >> left to right
< <= > >= left to right
== != left to right
& left to right
^ left to right
| left to right
&& left to right
|| left to right
? : right to left
= += -= *= /= %= >>= <<= &= ^= |= right to left
Chapter 12 Structure and ADTs 19
Structures, Functions, and Assignment
Structures as Argument– call-by-value 로 struct 가 copy 되어 사용 된다 .
[Ex] struct card { int pips; char suit;}c1 = {5, ’d’};
: assign_values(c1);
printf(“%d %c”, c1.pips, c1.suit); :
void assign_values(struct card c) { c.pips = 1; c.suit = ‘c’;}
parameter 를 struct card c 로사용할 경우 struct 가 memory 에
복사하게 되므로 call-by-value 가 되어 return 후 변경된 값이 유지 되지 않는다 .
5 d
Chapter 12 Structure and ADTs 20
Structures, Functions, and Assignment
Struct pointer 사용– call-by-reference 로 struct 의 address 를 전달한다 .
[Ex] struct card { int pips; char suit;}c1 = {5, ’d’};
: assign_values(&c1);
printf(“%d %c”, c1.pips, c1.suit); :
void assign_values(struct card *c) { c->pips = 1; c->suit = ‘c’;}
parameter 를 struct card *c 로사용할 경우 struct 의 address 가
전달되어 call-by-reference 가 되므로 return 후 변경된 값이 유지 된다 .
1 c
Chapter 12 Structure and ADTs 21
Structure 사용
5
d 5
d
main() assign_values()
Structure 의 copy
X 1
X c
Structure Pointer사용
5
d
main()
Address 의 copy
같은 structure의 point X 1
X c
assign_values()
Structures, Functions, and Assignment
Call -by-Value Call -by-Reference
Chapter 12 Structure and ADTs 22
Structures, Functions, and Assignment
Structures Pointer 사용[Ex] struct card {
int pips; char suit;
};
void assign_values(struct card *c_ptr, int p, char s) { c_ptr -> pips = p;
c_ptr -> suit = s; }
void extract_values(struct card *c_ptr, int *p_ptr, char *s_ptr) { *p_ptr = c_ptr -> pips; *s_ptr = c_ptr -> suit;
}
Chapter 12 Structure and ADTs 23
Structures, Functions, and Assignment
[Ex] void prn_values(struct card *c_ptr) { int p; char s; char *suit_name; extract_values(c_ptr, &p, &s); switch(s) { case ‘c’ :
suit_name = “clubs”; break; case ‘d’ :
suit_name = “diamonds”; break; case ‘h’ :
suit_name = “hears”; break; case ‘s’ :
suit_name = “spades”; break; default :
suit_name = “error”; } printf(“card: %d of %s \n”, p, suit_name);}
Chapter 12 Structure and ADTs 24
Structures, Functions, and Assignment
[Ex] int main(void) { int i; struct card deck[52];
for( i = 0; i < 13; i++) {assign_values(deck + i, i + 1, ‘c’ );assign_values(deck + i + 13, i + 1, ‘d’ );assign_values(deck + i + 26, i + 1, ‘h’ );assign_values(deck + i + 39, i + 1, ‘s’ );
}
for( i = 0; i < 13; i++) /* print out the hearts */prn_values(deck + i + 26);
return 0;}
card : 1 of heartscard : 2 of hearts :card : 13 of hearts
&deck[ i+13] 와 같은 표현으로struct 의 address 를 전달
Chapter 12 Structure and ADTs 25
Problem Solving : Student Records
Nested Structure
[Ex] struct person_name { char first[10]; char middle_initial; char last[10];};
struct student { struct person_name name ; int id, age; char sex; } student1, student2;
student1
student1.name.middle_initial student1.id
student1.name.first
student1.name.laststudent1.age student1.sex
Chapter 12 Structure and ADTs 26
Problem Solving : Student Records
Nested Structure– nested member name 으로 access 가능
– 정의된 member ‘name’ 으로 access 가능
[Ex] strcpy ( student1.name.first, “Fred”) ;strcpy ( student1.name.last, “Gordon”) ;
[Ex]display_name ( student1.name); /* 하나의 argument 로 사용 가능 */
struct person_name new_name={“Young”,’s’, “Kim”} ;student1.name = new_name ; /* 같은 struct 로 assignment 가능 */
Chapter 12 Structure and ADTs 27
Problem Solving : Student Records
[Ex]
void display_name ( struct person_name name) { printf(“name : %s %c. %s\n”,
name.first, name.middle_initial, name.last);}
void display(struct student s) {printf(“id : %d\n”, s.id);display_name(s.name);printf(“age : %d\n”, s.age);printf(“gender : %c”, s.gender);
}
Chapter 12 Structure and ADTs 28
Problem Solving : Student Records
Arrays of Structure[Ex] struct part int number; char name[10]; int on_hand; } inventory[100];
inventory[0]
inventory[0].number inventory[0].on_hand
1 Monitor 10
inventory[1]
inventory[1].number inventory[1].on_hand
5 Memory 53 ………
inventory[0].name
inventory[1].name
Chapter 12 Structure and ADTs 29
Problem Solving : Student Records
[Ex] #define CLASS_SIZE 50#define NCOURSES 10
struct student { char *last_name; int student_id;
char grade;};
struct date { short day; char month[10]; short year;};
struct personal { char name[20]; struct date birthday;};
Chapter 12 Structure and ADTs 30
Problem Solving : Student Records
struct student_data { struct personal p; int student_id; char grade[NCOURSES];};
[Ex] /* struct date type 의 variable 에 data 를 입력받음 */
void read_date(struct date *d) { printf(“Enter day(int) month(string) year(int) : “); scanf(“%hd%s%hd”, &d->day, d->month, &d->year);}
:struct student_data temp;read_date(&temp.p.birthday);
struct personalstruct date
&(d->day) 와 같은 표현
Chapter 12 Structure and ADTs 31
Problem Solving : Student Records
[Ex] /* student_data type 의 member 중 char[ ] grade 를 입력받음 */
void read_grades(char g[ ]) { int i; printf(“Enter %d grades: “, NCOURSES); for( i = 0; i < NCOURSES; ++i)
scanf(“ %c”, &g[ i]);}
:
read_grades(temp.grade);
char[ ] type:array name 은 array 의 base address 를
나타내는 char pointer 로call-by-reference 가 된다 .
Chapter 12 Structure and ADTs 32
Problem Solving : Student Records
[Ex] /* struct student_data type variable 의 information 을 struct student 의 variable 에 convert */
#define C_PROGRAMMING 0#define UNIX 1
void extract (struct student_data *s_data, int n, struct student *undergrad) {
undergrad -> student_id = s_data -> student_id; undergrad -> last_name = s_data -> p.name; undergrad -> grade = s_data -> grade[n];}
: struct student_data temp;
struct student student[100];extract(&temp, C_PROGRAMMING, &student[0]);
Chapter 12 Structure and ADTs 33
Initialization of Structures
Initializing an array of Structures
[Ex] struct dialing_code { char *country; int code;
} ;
const struct dialing_code country_codes[ ] = { {“Argentina”, 54},
{“Bangladesh”, 880}, {“Korea”, 82},
: } ;
Array size 는 compiler 에 의해 자동 삽입
Chapter 12 Structure and ADTs 34
Initialization of Structures
Initializing a nested Structures
struct student st = { {"Kim", 's', "Handong"}, 197001, 25, 'T'
};
Array size 는 compiler 에 의해 자동 삽입
[Ex] struct person_name { char first[10]; char middle_initial; char last[10];};
struct student { struct person_name name ; int id
int age; char sex; };
Chapter 12 Structure and ADTs 35
The Use of typedef
The use of typedef– data type 의 name 을 재 정의 하기 위해 사용– readability 의 증가
[Ex] #define N 3 /* size of all vectors and matrices */
typedef double scalar;typedef scalar vector[N];typedef scalar matrix[N][N];
typedef vector maxrix[N]와 같은 표현
double 의 1 차원 array type 의 vector 선언
[Ex] void add(vector x, vector y, vector z) { int i; for( i = 0 ; i < N; ++i)
x[ i ] = y [ i ] + z [ i ];}
Chapter 12 Structure and ADTs 36
The Use of typedef
[Ex] scalar dot_product(vector x, vector y) { int i; scalar sum = 0.0;
for(i = 0; i < N; ++i) sum += x[ i] * y [ i];
return sum;}
void multiply(matrix a, matrix b, matrix c) { int i, j, k;
for(i = 0; i < N; ++i) for(j = 0; j< N; ++j ) { a[ i][ j] = 0.0; for( k = 0; k < N; ++k) a[ i][ j] += b[ i][ k] * c[ k][ j];}
}
double sum=0.0; 과 동일
double a[N][N] 과 동일
Chapter 12 Structure and ADTs 37
typedef 를 사용 , struct type 을 새로운 type 으로 선언[Ex] typedef struct {
int number; char name[20]; int on_hand;
} part;
part part1, part2
The Use of typedef
새로운 type part 가 정의
[Ex] struct part { int number; char name[20]; int on_hand;
};
typedef struct part part;
새로운 type part 가 정의
Chapter 12 Structure and ADTs 38
The Use of typedef
[Ex] typedef struct part part;
struct part p1;part *p2 = &p1;
:display1(&p1);display2(&p1);
display1(p2);display2(p2);
void display1 (struct part* p) { printf(“%d, %s, %d”, p->number, p->name, p->on_hand);}
void display2 (part* p) { printf(“%d, %s, %d”, p->number, p->name, p->on_hand);}
Chapter 12 Structure and ADTs 39
Self-Referential Structures– struct member 중에 같은 struct type 을 reference
하는 pointer 를 가지고 있음
– compatible, 즉 같은 type 의 structure 를 link 하기 위해 사용
[Ex] struct list { int data; struct list *next;
}
Self-Referential Structures
next 를 통해서 같은 type 의 다른 structure 와 연속적으로 link 됨
data next
Chapter 12 Structure and ADTs 40
[Ex] struct list a, b, c;
a.data = 1;b.data = 2;c.data = 3;a.next = b.next = c.next = NULL; /* Point nothing */
Self-Referential Structures
NULL1
a
NULL2
b
NULL3
c
data next data next data next
Chapter 12 Structure and ADTs 41
[Ex] a.next = &b;
b.next = &c;
printf(“%d\n”, a.next -> data); /* b.data */
printf(“%d\n”, a.next -> next -> data ); /* c.data */
Self-Referential Structures
1
a
2
b
NULL3
c
data next data next data next
2 3
Chapter 12 Structure and ADTs 42
Linear Linked List– 여러 개의 structure 가 연속적으로 link
– structure 는 data part 와 address part 로 구성된다 .
– Address part 는 같은 type 의 structure 를 point 하는 member 로 구성된다 .
– head 는 첫번째 Element 를 point
– 각각의 Element 는 다음의 Element 를 point
– 마지막 Element 의 address part 는 NULL
– Element 는 dynamic allocation 에 의해 생성된다 .
Linear Linked Lists
NULL
headdata data dataaddres
saddres
saddres
s
Chapter 12 Structure and ADTs 43
Linear Linked Lists
[Ex] /* filename : list.h */
#include <stdio.h>
typedef char DATA;
struct linked_list { DATA d; struct linked_list *next;}
typedef struct linked_list ELEMENT; typedef ELEMENT * LINK;
stdio.h 에서 NULL 을 define
linked list 를 구현하기 위한type 을 정의하고 있는head file ‘list.h’ 작성
Chapter 12 Structure and ADTs 44
Dynamic Allocation
Creates Element list
Linear Linked Lists
[Ex] LINK head;head = (LINK)malloc(sizeof(ELEMENT));/* head 는 할당된 ELEMENT type 의 struct 를 point */
system 으로부터 ELEMENT type 의 struct 를 저장하기 위한 memory 할당
[Ex] LINK head;head = (LINK)malloc(sizeof(ELEMENT));
head -> d = ‘n’; /* data part 에 data 입력 */head -> next = NULL; /* address part 를 초기화 */
‘n’ NULL
head
Chapter 12 Structure and ADTs 45
Linear Linked Lists
[Ex] head -> next =(LINK) malloc(sizeof(ELEMENT));head -> next -> d = ‘e’;head -> next -> next = NULL;
‘n’
head
‘e’ NULL
[Ex] head -> next -> next = (LINK)malloc(sizeof(ELEMENT));head -> next -> next -> d = ‘w’;head -> next -> next -> next = NULL;
‘e’
head
‘w’ NULL‘n’
New element 의 생성 및 list 에 추가
Chapter 12 Structure and ADTs 46
List Operations
[Ex] /* List creation by recursion */
#include “list.h”
LINK string_to_list(char s[ ]) { LINK head;
if(s[ 0] == ‘\0’) /* base case */return NULL;
else {head = (LINK)malloc(sizeof(ELEMENT));head -> d = s [0];head -> next = string_to_list[s+1];return head;
}}
다음 Element 의 address 또는NULL 을 return
String(‘s’) 을 입력 받아char 를 data 로 하는
linked list 를 생성하는 function
Chapter 12 Structure and ADTs 47
List Operations[Ex] /* List creation by iteration */
#include “list.h”
LINK string_to_list(char s[ ]) { LINK head, temp; int i=0;
if(s[ 0] == ‘\0’) return NULL;
head = (LINK)malloc(sizeof(ELEMENT)); head -> d = s[ 0]; head -> next = NULL; temp = head;
while(s[++i] != ‘\0’) {temp -> next = (LINK)malloc(sizeof(ELEMENT));temp = temp -> next;temp -> d = s [ i];temp -> next = NULL;
} return head;}
String 을 입력 받아char 를 data 로 하는
linked list 를 생성하는 function
Chapter 12 Structure and ADTs 48
Counting
Counting and Lookup
[Ex] /* count the elements in a list recursively */
#include “list.h”
int count(LINK head) {
if(head == NULL) /* base case */return 0;
elsereturn ( 1 + count(head->next) );
}
Chapter 12 Structure and ADTs 49
Counting and Lookup
[Ex] /* count the elements in a list by iteration */
#include “list.h”
int count(LINK head) {
LINK temp = head; int cnt = 0; while(temp != NULL) {
cnt++; temp = temp -> next } return cnt;}
Chapter 12 Structure and ADTs 50
Lookup
Counting and Lookup
[Ex] /* Lookup c in the list pointed to by head (recursion)*/
#include “list.h”
LINK lookup(DATA c, LINK head) {
if(head == NULL) /* 없는 경우 */return NULL;
else if( c == head -> d) /* 찾은 경우 */ return head;
else /* 그 다음 element 의 search */return (lookup(c, head-> next));
}
Chapter 12 Structure and ADTs 51
Counting and Lookup
[Ex] /* Lookup c in the list pointed to by head (iteration)*/
#include “list.h”
LINK lookup(DATA c, LINK head) {
LINK temp = head;
while(temp != NULL) {if( c == temp -> d) return temp;temp = temp -> next;
} return NULL;}
Chapter 12 Structure and ADTs 52
Insertion
– before insertion
– after insertion
Insertion and Deletion
[Ex] #include “list.h”void insert(LINK p1, LINK q) { /* p1 뒤에 q 를 insert */ q -> next = p1 -> next; p1 -> next = q;}
B NULL
p1C NULLA
q
B
p1C NULLA
q
Chapter 12 Structure and ADTs 53
Deletion
– before deletion
– after deletion
Insertion and Deletion
[Ex] #include “list.h”void delete(LINK p1, LINK q) { /* p1 뒤의 q 를 delete */ p1 -> next = q -> next; free(q);}
Bp1
C NULLA
q
Bp1
C NULLA
q
System 이 memory 를 사용할 수 있도록 q 가 reference 하는 부분을 해제시킴
즉 그 영역은 다시 free 가 되어 다른 program 에서 그 영역의 사용 가능
free
Chapter 12 Structure and ADTs 54
Insertion and Deletion
[Ex] /* Recursive deletion of a list */
#include “list.h”
void delete_list(LINK head) {
if(head != NULL) {delete_list(head -> next);free(head);
}} List 의 모든 element 삭제
Chapter 12 Structure and ADTs 55
Insertion and Deletion
[Ex] /* Iterative deletion of a list */
#include “list.h”
void delete_list(LINK head) {
LINK temp;
if(head != NULL) {temp = head;head = head -> next;free(temp);
}}
List 의 모든 element 삭제
Chapter 12 Structure and ADTs 56
Displaying list
[Ex] /* Display all elements in a list */
#include “list.h”
void display(LINK head) {
LINK temp = head;
while(temp != null) {printf(“ELEMENT (at %p)”, temp);
printf(“\tDATA : %c”, temp -> d);printf(“\tnext : %p\n”, temp -> nexttemp = temp -> next;
}}
List 의 모든 element 를 출력
Chapter 12 Structure and ADTs 57
[Ex] /* Sample main( ) */
#include “list.h”
LINK string_to_list(char[ ] s);void display(LINK head);
:
int main(void) {
char s[10] = "Handong"; LINK head;
head = string_to_list(s); display(head);}
ELEMENT (at 20a78) DATA : H next : 20a88ELEMENT (at 20a88) DATA : a next : 20a98ELEMENT (at 20a98) DATA : n next : 20aa8ELEMENT (at 20aa8) DATA : d next : 20ab8ELEMENT (at 20ab8) DATA : o next : 20ac8ELEMENT (at 20ac8) DATA : n next : 20ad8ELEMENT (at 20ad8) DATA : g next : 0
string 으로 linked list 를 생성하고list 의 모든 element 를
출력하는 program
Displaying list
수고하셨습니다 .
Structure and ADTs