Lecture 6 • C로 복잡한 구조의 값 표현하기 – array, struct, dynamic memory allocation • 메모리 관리하기 – malloc, free • 복잡한 구조 프로그래밍 기술 – value oriented v. s. object oriented
복잡한 구조의 값 표현하기: struct x id age highschool
malloc (1/2) malloc: INT -> LOC 할당할 byte 갯수 할당된 메모리 시작주소 혹은 0 malloc(4); malloc(sizeof(int)); malloc(12); malloc(sizeof(int)*3); malloc(13);
free (2/2) • int x; x = 1; free(x); • struct {Mass kg; Force hp; } x; x. kg = 1; x. hp = 0. 2; free(x); • int *x = malloc(sizeof(int) * 10); *x = 1; *(x+1) = 2; free(x); • free(x+1); • free(x); … free(x); 주의! null dereference
typedef • 타입에 이름 짓기 – typedef int Mass; – typedef float Force; – typedef struct {Mass kg; Force hp; } Man; • 사용 – Man x; Man x[10]; Force f; Mass m; – struct {Mass kg; Force hp; } y; – malloc(sizeof(Mass)); malloc(sizeof(Man));
struct malloc • 타입정의 typedef struct {Mass kg; Force hp; } Man; • 사용 Man *x; x = malloc(sizeof(Man)); x->kg = 70; (*x). hp = 0. 1;
array = pointer • 같은 선언 – int a[10]; – int *a = malloc(sizeof(int)*10); • 같은 사용 a[0] = 1; a[1] = 2; x = a[1]; *(a+0) = 1; *a = 1; *(a+1) = 2; x = *(a+1);
타입 변환 type casting (1/2) • 타입 변환: type A의 값을 type B의 값으로 • 어떻게: (<type B>)<type A의 값을 계산하는 식> – (float)0; (double)2. 0; • sizeof(B) >= sizeof(A) 이면 ok. • sizeof(B) < sizeof(A) 이면? – 번역기(compiler)나 실행되는 기계에 따라 다름 – int x; float y = 1. 89; x = (int)y; – x has 1 for KX-II, 2 for machine WS 4
타입 변환 type casting (2/2) • sizeof of location/pointer is equal for any • sizeof(<type>*) is equal for any <type> • 따라서, – (char *)malloc(sizeof(Man)) – (man *)malloc(sizeof(Man)) – (car *)malloc(sizeof(Man)) – malloc 은 default로 void* 를 줌