Week 7-1. 구조체와 유니온 [Download]

Download Report

Transcript Week 7-1. 구조체와 유니온 [Download]

구조체 (Structure)
공용체 (Union)
2003. 4. 17.
Structure type

structure
– 두개 이상의 서로 다른 원소로 구성된
통합자료형
– 여러 가지 항목을 가진 객체를 변수로
만들고 싶을 때 사용
– 배열과의 차이점-배열은 동일한
자료형으로된 기억 장소들만을 모아 놓고
관리하는데
2
Structure type
형식:
struct tag_name {
type element1;
type element2;
type element3;
. . .
} variable-list;
3
Structure type
예:
struct catalog {
char name[40];
char title[40];
char pub[40];
int date;
} card;
char name[20]
struct
catalog
char title[40]
char pub[40]
int date
4
구조체 변수 선언/접근

구조체 변수선언
– 방법1) struct catalog var1, var2, var3;
– 방법2)
• typedef struct catalog CATALOG
• CATALOG var1, var2, var3;

구조체에 대한 접근: .(dot) 연산자 사용
– date field에 1994를 저장하기 위해서
• card.date= 1994;
–
–
–
–
–
–
scanf("%u", &card.date);
printf("%u", card.date);
gets(card.name);
...
printf("%s",card.title);
printf("%c", card.title[2]);
5
구조체 변수 선언/접근

구조체형 배열의 선언
– struct catalog cat[100];
• sizeof(struct catalog) 크 기 의
catalog
구조체형이 100개가 연결된 구조체형의 배열

구조체형 배열의 접근
– printf("%s", cat[4].title);
6
예제
#include <stdio.h>
struct AT{
char *irum;
int nai;
};
void main()
{
struct AT A[3]=
{{"jun",2},{"you sun",4},{"yun su",5}};
int i;
for(i=0;i<=2;i++)
printf("%10s%10d\n",A[i].irum,A[i].nai);
puts(" the end");
}
7
구조체 변수 할당

구조체 변수의 내용을 동일한 형의 다른
구조체 변수에 치환 가능
struct s_type {
int a;
float f;
} var1, var2;
var1.a= 10;
var1.f= 100.23;
…
var2= var1;
8
예제
#include "stdio.h"
struct s_type {
int i;
char ch;
double d;
char str[80];
} s;
void main(void)
{
scanf("%d %c %lf %s", &s.i, &s.ch, &s.d, &s.str);
printf("%d %c %lf %s", s.i, s.ch, s.d, s.str);
printf("size
of
s_type
sizeof(struct s_type);
is
%d
bytes
long\n",
}
9
예제
#include <stdiio.h>
struct s_type {
int i;
double d;
} var1;
struct s_type(void)
{
struct s_type temp;
temp.i = 100;
temp.d = 123.123;
struct s_type f(void);
return temp;
}
main()
{
var1 = f();
printf("%d %lf", var1.i, var1.d");
}
10
구조체 포인터

포인터를 통해 구조체를 접근하는 것이
일반적
struct s_type {
int i;
char str[80];
} s, *p;
. . .
p= &s;

arrow operator를 사용하여 접근
– p->i= 1;

(s.i= 1; 의 표현과 동일)
구조체를 함수에
포인터를 사용
전달하기
위해서는
– 구조체 변수 자체 또한 인자로 전달 가능
– 그러나, …
11
구조체 포인터

구조체 변수 자체를 함수 입력
매개변수로 넘기는 경우,
– structure의 크기가 클 때는 인자를
복사하는데 시간이 많이 걸리고
공간상으로도 낭비이므로 주로
structure의 포인터를 인자로 주는 방법을
사용
12
예제
#inlcude "stdio.h"
#include "string.h"
struict s_type {
int i;
char str[80];
} s, *p;
void main()
{
p = &s;
s.i = 10;
p->i = 10;
strcpy(p->str, "I like you");
}
printf("%d, %d, %s", s.i, p->i, p_str);
13
예제
struct complex{
double re;
double im;
};
typedef struct complex complex;
void add(complex *a, complex *b, complex *c)
{
a->re = b->re + c->re;
a->im = b->im + c->im;
}
a->re는
(*a).re와
같은 의미
14
다중 구조체

구조체의 구성원이 다른 구조체인 경우
– 예: 한 조립라인에 10명의 작업자가 일하는 두 개의
조립라인에 대한 정보를 저장하기 위해
#define NUM_ON_LINE
10
struct asm_line {
int product_code;
double material_cost;
struct worker {
char name[80];
struct worker wkers[NUM_ON_LINE];
} line1, line2;
int avg_units_per_hour;
int avg_errs_per_hour;
};
사용 예:
line1.wkers[1].avg_units_per_hour=
12;
15
예제
#include <stdio.h>
struct AT{
int kor;
int eng;
};
struct BT{
char *irum;
struct AT tit;
};
main()
{
struct BT B[3] = {{"dong",100,20
printf("%10s%5s%5s%7s\n\n","name","kor","eng","avg");
for(i=0;i<=2;i++)
printf("%10s%5d%5d%7.1f\n",
B[i].irum,B[i].tit.kor,
B[i].tit.eng,(B[i].tit.kor +B[i].tit.eng)/2.);
}
16
Unions

두 개 이 상의 변 수에 의 해 공 유 되 는
메모리 영역
union u_type {
union tag-name {
type element1;
type element2;
. . .
type elementN;
} variable-names;
int i;
char c[2];
double d;
d
c[0] c[1]
i
} sample;
17
Unions

공용체의 접근은
– 구조체와 동일하다

공용체의 크기는 컴파일 시에 결정
– 가장 큰 원소를 수용하기에 충분한 공간
확보
18
예제
#include "stdio.h"
int encode(int i);
void main(void)
{
int i;
i= encode(10);
printf("10 is encoded -> %d \n",i);
i= encode(10);
printf("i is decoded -> %d \n",i);
}
int encode(int i)
{
union crypt_type {
short num;
char c[2];
} crypt;
char ch;
crypt.num= i;
ch= crypt.c[0];
crypt[0]= crypt[1];
crypt.c[1]= ch;
return(crypt.num);
}
19
예제
ap=&B[0];
ap->nai=10;
ap++;
ap->ki=120.5;
ap++;
ap->nai=20;
ap-=2;
#include <stdio.h>
main()
{
union AT{
int nai;
float ki;
};
union AT *ap;
union AT B[3];
printf("%4d %6.1f %4d\n",
B[0].nai,B[1].ki,B[2].nai);
printf("%4d",ap->nai);
ap++;
printf("%6.1f",ap->ki);
ap++;
printf("%4d\n",ap->nai);
}
20