Algorithms

Similar documents
Microsoft PowerPoint - 03_(C_Programming)_(Korean)_Pointers

Microsoft PowerPoint - 07_(C_Programming)_(Korean)_Composite_Data_Types

슬라이드 1

Microsoft PowerPoint - 08_(C_Programming)_(Korean)_Preprocessing

Microsoft PowerPoint - 06_(C_Programming)_(Korean)_Characters_Strings

C++ Programming

PowerPoint 프레젠테이션

K&R2 Reference Manual 번역본

금오공대 컴퓨터공학전공 강의자료

[ 마이크로프로세서 1] 2 주차 3 차시. 포인터와구조체 2 주차 3 차시포인터와구조체 학습목표 1. C 언어에서가장어려운포인터와구조체를설명할수있다. 2. Call By Value 와 Call By Reference 를구분할수있다. 학습내용 1 : 함수 (Functi

Microsoft PowerPoint - 09_C_Language_Pointer_Advanced

<322EBCF8C8AF28BFACBDC0B9AEC1A6292E687770>

Microsoft PowerPoint - ch07 - 포인터 pm0415

< E20C6DFBFFEBEEE20C0DBBCBAC0BB20C0A7C7D12043BEF0BEEE20492E707074>

Microsoft PowerPoint - chap10-함수의활용.pptx

OCW_C언어 기초

Microsoft PowerPoint - chap03-변수와데이터형.pptx

untitled

설계란 무엇인가?

Microsoft PowerPoint - chap13-입출력라이브러리.pptx

11장 포인터

PowerPoint 프레젠테이션

11장 포인터

Microsoft PowerPoint - chap06-2pointer.ppt

Microsoft PowerPoint - chap06-1Array.ppt

목차 포인터의개요 배열과포인터 포인터의구조 실무응용예제 C 2

제 14 장포인터활용 유준범 (JUNBEOM YOO) Ver 본강의자료는생능출판사의 PPT 강의자료 를기반으로제작되었습니다.

Microsoft PowerPoint - chap02-C프로그램시작하기.pptx

C++ Programming

Microsoft PowerPoint - chap11-포인터의활용.pptx

금오공대 컴퓨터공학전공 강의자료

<4D F736F F F696E74202D20C1A63132B0AD20B5BFC0FB20B8DEB8F0B8AEC7D2B4E7>

1 장 C 언어복습 표준입출력배열포인터배열과포인터함수 const와포인터구조체컴파일러사용방법 C++ 프로그래밍입문

Microsoft PowerPoint - chap12-고급기능.pptx

C++ Programming

윤성우의 열혈 TCP/IP 소켓 프로그래밍

Microsoft PowerPoint - [2009] 02.pptx

13 주차문자열의표현과입출력

이번장에서학습할내용 동적메모리란? malloc() 와 calloc() 연결리스트 파일을이용하면보다많은데이터를유용하고지속적으로사용및관리할수있습니다. 2

기초컴퓨터프로그래밍

Microsoft PowerPoint - 3ÀÏ°_º¯¼ö¿Í »ó¼ö.ppt

슬라이드 1

A Dynamic Grid Services Deployment Mechanism for On-Demand Resource Provisioning

Microsoft PowerPoint - Chapter_08.pptx

Microsoft PowerPoint - 08-C-App-19-Quick-Preprocessor

Microsoft PowerPoint - chap-11.pptx

Data Structure

OCW_C언어 기초

11장 포인터

02장.배열과 클래스

Microsoft PowerPoint - 08_C_Language_Preprocessor

untitled

YRRZBRRLMCEQ.hwp

Microsoft PowerPoint - ch07 - 포인터 pm0415

Microsoft PowerPoint - 제11장 포인터

Microsoft PowerPoint - 제11장 포인터(강의)

Microsoft PowerPoint - chap06-5 [호환 모드]

untitled

歯9장.PDF

제 11 장포인터 유준범 (JUNBEOM YOO) Ver 본강의자료는생능출판사의 PPT 강의자료 를기반으로제작되었습니다.

KNK_C_05_Pointers_Arrays_structures_summary_v02


Microsoft PowerPoint - 10장 문자열 pptx

PowerPoint 프레젠테이션

Microsoft PowerPoint 자바-기본문법(Ch2).pptx

구조체정의 자료형 (data types) 기본자료형 (primitive data types) : char, int, float 등과같이 C 언어에서제공하는자료형. 사용자정의자료형 (user-defined data types) : 다양한자료형을묶어서목적에따라새로운자료형을

Microsoft PowerPoint - Chapter_04.pptx

Infinity(∞) Strategy

chap7.key

프로그램을 학교 등지에서 조금이라도 배운 사람들을 위한 프로그래밍 노트 입니다. 저 역시 그 사람들 중 하나 입니다. 중고등학교 시절 학교 도서관, 새로 생긴 시립 도서관 등을 다니며 책을 보 고 정리하며 어느정도 독학으르 공부하긴 했지만, 자주 안하다 보면 금방 잊어

PowerPoint Presentation

PowerPoint Template

Microsoft PowerPoint - chap06.ppt

ABC 6장

학습목차 2.1 다차원배열이란 차원배열의주소와값의참조

<4D F736F F F696E74202D20C1A63137C0E520B5BFC0FBB8DEB8F0B8AEBFCD20BFACB0E1B8AEBDBAC6AE>

0. 표지에이름과학번을적으시오. (6) 1. 변수 x, y 가 integer type 이라가정하고다음빈칸에 x 와 y 의계산결과값을적으시오. (5) x = (3 + 7) * 6; x = 60 x = (12 + 6) / 2 * 3; x = 27 x = 3 * (8 / 4


Microsoft PowerPoint - chap06-8.ppt

Microsoft PowerPoint - 04_C_Language_Function

Microsoft PowerPoint - chap06-8 [호환 모드]

슬라이드 1

Microsoft PowerPoint - chap04-연산자.pptx

C Programming

C 언어 프로그래밊 과제 풀이

목차 배열의개요 배열사용하기 다차원배열 배열을이용한문자열다루기 실무응용예제 C 2

Microsoft PowerPoint - chap05-제어문.pptx

8장. 포인터

ch15

윤성우의 열혈 TCP/IP 소켓 프로그래밊

Microsoft PowerPoint - 제9강 문자열

PowerPoint Presentation

Microsoft PowerPoint - ch01.ppt

Microsoft PowerPoint - chap08-1 [호환 모드]

Microsoft PowerPoint - C프로그래밍-chap03.ppt [호환 모드]

Microsoft PowerPoint - Chapter14_17.pptx

Microsoft PowerPoint - Lesson14.pptx

Microsoft PowerPoint - Lesson14.pptx

슬라이드 1

Transcription:

자료구조 & 알고리즘 C 프로그래밍기법 Seo, Doo-okok clickseo@gmail.com http://www.clickseo.com

목 차 C 언어기본문법 제어흐름 포인터의이해 함수, 배열, 문자열 유도형 유도형 : 구조체, 공용체, 열거형 전처리 포인터응용 2

변수 (variable) C 언어기본문법 프로그램에서사용되는자료를저장하기위한공간 할당받은메모리의주소대신부르는이름 사용자가변수이름을만들어저장하기위한자료의형태를지정하면컴파일러는 컴퓨터의메인메모리에주소값과연결시켜준다. 프로그램실행중에값변경가능하다. 사용되기이전에선언되어야한다. 1000 A ch 2000 char ch; int i; 1001 1002 1003 2001 2002 2003 100 i 프로그램 메모리 3

상수 (constant) C 언어기본문법 (cont d) 프로그램수행중에변하지못하는자료값 실제값상수 정수형상수 (integer constant) 실수형상수 (real constant) 문자형상수 (character constant) 문자열상수 (string constant) 기억장소를갖는상수 선언하는것은변수선언과똑같지만앞에 const 키워드를써야하고반드시 초기값이있어야한다는것이다르다. 4

C 언어기본문법 (cont d) 기본형 문자형정수형실수형형없음 char, unsigned char short, unsigned short int, unsigned int long, unsigned long long long, unsigned long long float, double, long double void 구조를갖는형 열거형 배열형구조체공용체 [ ] struct union enum 포인터형 * 5

콘솔입출력함수 C 언어기본문법 (cont d) 함수의선언기능헤더파일 int getchar(void); 한문자를읽어들인다. int putchar(int ch); 한문자를출력한다. char *gets(char *str); 문자열을읽어들인다. int puts(char *str); 문자열을출력한다. stdio.h int printf(char *control-string,...); 문자열을서식을갖춰출력 int scanf(char *control-string,...); int getch(void); int putch(void); int getche(void); int kbhit(void); 문자열을서식을갖춰입력입력화면에입력문자는표시안된다 ( 비표준문자입력함수 ). putchar() 와달리 \n 을CR/LF의조합으로바꾸지않는다 ( 비표준문자출력함수 ). 입력문자가화면에출력 ( 에코 ) 된다 ( 비표준문자입력함수 ) 키의눌림여부를조사한다. 눌린경우 0이아닌수를반환한다 ( 비표준키입력함수 ). conio.h 6

C 언어기본문법 (cont d) 우선순위와결합성 기능별분류연산자결합성우선순위 일차연산자 ( ) [ ] ->. 1 단항연산자 + - ++ --! ~ * & sizeof (datatype) 2 산술연산자 * / % 3 + - 4 시프트연산자 << >> 5 비교연산자 < <= > >= 6 등가연산자 ==!= 7 & 8 비트논리연산자 ^ 9 논리연산자 10 && 11 12 조건연산자? : 13 대입연산자 = += -= *= /= %= >>= <<= &= ^= = 콤마연산자, 15 14 7

제어흐름 프로그램예제 : if else 문과삼원조건식 #include <stdio.h> int main(void) int a, x = 3, y = 4; if(x < y) a = x; else a = y; a = (x < y)? x : y; printf("a = %d\n", a); return 0; 8

프로그램예제 : switch 문사용예제 #include <stdio.h> int main (void) int score, temp; char grade; 제어흐름 (cont d) printf("0 ~ 100 사이의점수를입력하시오 : "); scanf ("%d", &score); temp = score / 10; switch (temp) case 10: case 9 : grade = 'A'; case 8 : grade = 'B'; case 7 : grade = 'C'; case 6 : grade = 'D'; default : grade = 'F'; printf( \n학점 : %c \n", grade); break; break; break; break; return 0; 9

프로그램예제 : else-if 문사용예제 #include <stdio.h> int main (void) int score; char grade; 제어흐름 (cont d) printf("0 0 ~ 100 사이의점수를입력하시오 : "); scanf ("%d", &score); if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else grade = 'F'; printf( \n 학점 : %c \n", grade); return 0; 10

for 문과 while 문 제어흐름 (cont d) #include <stdio.h> #include <stdio.h> int main(void) int i; i = 0; 초기문 int main(void) int i; while ( i < 10 ) 조건문 for(i = 0; i < 10; i++) printf( Hello World!! n ); printf( Hello World!! n ); i++; 증감문 return 0; return 0; 11

do while 문 수행후검사루프 세미콜론 (;) 으로끝난다. 제어흐름 (cont d) do do ( 실행할명령문 ) while ( 조건식 ); ( 실행할명령문 ) while ( 조건식 ); 12

점프문 (Jump Statement) 제어흐름 (cont d) goto 문은구조적프로그래밍에적합하지않다. 점프문 break continue return goto 13

포인터를통한변수접근 // 변수와포인터변수선언 포인터의이해 int a; 0x12FF70 10 int *p; p 0x12FF78 a 0x12FF70 // 변수와포인터변수의초기화 a = 10; p = &a; *p a 100 // 변수 a 의데이터값 P &a 0x12FF70 // 변수 a 의주소 a = a + 1; a++; *p =*p +1; (*p)++; 14

포인터의이해 (cont d) 프로그램예제 : 변수변경 -- 흥미로운포인터 #include <stdio.h> int main (void) int a, b, c; int *pa, *pb, *pc; a = 6; b = 2; pa = &b; pb = pa; pc = &c; pa = &a; *pb = 8; *pc = *pa; *pc = a + *pb + *&c; printf("a : %d, b : %d, c : %d \n", a, b, c); printf("*pa : %d, *pb : %d, *pc : %d \n", *pa, *pb, *pc); return 0; 15

void 형포인터란? 포인터의이해 void형포인터는어느것이든가리킬수있는포인터이다. void 형포인터 현재가리키고있는대상체의크기가정해져있지않은포인터 void *p; p char int double 16

함 수 여러개의함수로프로그램작성 #include <stdio.h> int ADD(int, int); int ADD(int a, int b) void main(void) int a, b, sum; int sum; scanf("%d %d", &a, &b); sum = a + b; sum = ADD(a, b); return sum; printf("%d + %d = %d n", a, b, sum); return 0; 17

함 수 (cont d) 프로그램예제 : 값에의한호출 -- swap 함수 #include <stdio.h> void SWAP(int, int); int main(void) int a = 10, b = 20; printf(" 호출전 : a = %d, b = %d \n", a, b); SWAP(a, b); printf(" 호출후 : a = %d, b = %d \n", a, b); temp return 0; void SWAP (int a, int b) int temp; temp = a; a = b; b = temp; b a b a??? 20 10 20 10 SWAP 함수스택영역 main 함수스택영역 18

함 수 (cont d) 프로그램예제 : 참조에의한호출 -- swap 함수 #include <stdio.h> void SWAP(int *, int *); int main(void) int a = 10, b = 20; printf(" 호출전 : a = %d, b = %d \n", a, b); SWAP(&a, &b); printf(" 호출후 : a = %d, b = %d \n", a, b); temp return 0; void SWAP (int *pa, int *pb) int temp; temp = *pa; *pa = *pb; *pb = temp; pb pa b a??? 0x0012ff74 0x0012FF70 20 10 SWAP 함수스택영역 main 함수스택영역 19

함 수 (cont d) 프로세스와프로그램 Memory stack max Mozilla Firefox Visual Studio heap data text 0 CPU 한글 2007 프로세스 : 운영체제에서프로세스는 실행중인프로그램 프로그램 : 컴퓨터를실행시키기위해차례대로작성된 명령어집합 저장장치 20

함 수 (cont d) 기억장소활용에따른변수의종류 변수의종류예약어생존기간유효범위초기화초기화값 자동변수 (auto) 일시적지역적수행시임의값 레지스터변수 register 일시적지역적수행시임의값 ( 내부 ) 정적변수 static 영구적지역적컴파일시 0 ( 외부 ) 정적변수 static 영구적전역적컴파일시 0 외부변수 (extern) 영구적전역적컴파일시 0 21

배 열 int arr[10]; 배열첨자 arr[0] 10 arr[1] 20 arr[2] 30 arr[3] 40 배열원소들... arr[4] arr[5] 50 60 arr[6] 70 arr[7] 80 arr[8] 90 arr[9] 100 arr 배열이름 22

배 열 (cont d) 1 차원배열과포인터 포인터연산의사용 p = arr + 5; 다른포인터에할당 간접연산자의사용 : a 가배열이름이고 n 이상수일때, 다음 2개의표현은완전히동일하다. arr [n] == * ( arr + n ) arr[0] == *(arr+0) arr[1] == *(arr+1) arr[2] == *(arr+2) arr[3] == *(arr+3) arr[4] == *(arr+4) 10 20 30 40 50 arr arr + 0 == &arr[0] arr + 1 == &arr[1] arr + 2 == &arr[2] arr + 3 == &arr[3] arr + 4 == &arr[4] 23

배 열 (cont d) 개별원소전달 arr[0] arr[1] arr[2] arr[3] arr[4] arr 10 20 30 40 50 #include <stdio.h> void PRINT (int); int main (void) int i; int arr[5] = 10, 20, 30, 40, 50; for (i=0;i<5;i++) return 0; PRINT (arr[i]); 함수가요구하는자료형과일치하는형을 값- 인수 (value parameter) 로전달된다. void PRINT (int a) printf( %3d, a); return; a 24

배 열 (cont d) 전체배열전달 #include <stdio.h> arr void PRINT (int x[]); 배열이름은 첫번째원소의시작주소 arr[0] arr[1] arr[2] arr[3] 10 20 30 40 int main(void) int arr[5] = 10, 20, 30, 40, 50; PRINT (arr); arr[4] 50 return 0; void PRINT (int p[]) int i; 함수정의의헤더부분의 p for (i=0;i<5;i++) 다음두문장은같다. printf( %3d, p[i]); printf( n ); int p[]; int *p; return; 25

문자열 문자와문자열상수 문자상수 : 문자상수를쓰려면작은따옴표 ( ) 를사용 문자열상수 : 문자열상수를쓰려면큰따옴표 ( )) 를사용 문자열은데이터자체는하나지만그뒤에구분자를쓸공간이필요하다. A A A A \0 문자 H 문자열 H (1 bytes) (2 bytes) 26

문자열초기화 문자열과포인터 (cont d) 포인터형변수에문자열의시작주소를할당 문자열을생성한후, 포인터형변수 p 에주소를저장 char *p = Click Seo ; Click Seo C l i c k S e o \0 p 27

문자열입출력함수 문자열입력함수 : gets, fgets 입력스트림에서한줄단위로읽어들여와널문자로끝나는문자열을생성한다. #include <stdio.h> char *gets (char *str); char *fgets (char *str, int size, FILE *fp); 호출성공 : str의주소를반환호출실패 : NULL 을반환 문자열출력함수 : puts, fputs 메모리에서널문자 ( \0) 로끝나는문자열을가져와출력스트림에 출력한다. #include <stdio.h> int puts (const char *str); int fputs (const char *str, FILE *fp); 호출성공 : 음수가아닌정수를반환호출실패 : EOF 를반환 28

문자열조작함수 문자열조작함수 문자열라이브러리 (<string.h>) 에존재한다. str 이라는접두사로시작한다. NULL : 널포인터상수 size_t : unsigned integer 타입 str (parameters) 문자열길이 : strlen 문자열의길이를반환 즉, 널문자를제외한문자열의문자개수를반환한다. #include <string.h> size_t strlen (const char *str); 29

문자열조작함수 (cont d) 문자열복사 : strcpy, strncpy 널문자를포함한원본문자열을목적지문자열로복사 #include <string.h> char *strcpy (char *str1, const char *str2); 원본문자열이목적지문자열보다길경우 메모리상목적지문자열뒤에있는데이터가파괴된다. 원본문자열보다목적지문자열이항상길도록만들어주어야만한다. #include <string.h> char *strncpy (char *str1, const char *str2, size_t n); 30

문자열조작함수 (cont d) 문자열비교 : strcmp, strncmp 두개의문자열을다른문자가나올때까지나끝이날때까지비교한다. #include <string.h> int strcmp (const char *str1, const char *str2); int strncmp (const char *str1, const char *str2, size_t size); 두가지함수는모두비교결과를정수로반환 : 두문자열이똑같으면 0 을반환 문자열연결 : strcat, strncat 한문자열을다른문자열의끝에추가하는기능을한다. #include <string.h> char *strcat (char *str1, const char *str2); char *strncat (char *str1, const char *str2, size_t size); 31

문자열조작함수 (cont d) 문자열에있는문자또는문자열 : strchr, strrchr, strstr #include <string.h> // 문자가문자열에존재하는지검색하는함수 char *strchr (const char *str, int ch); char *strrchr (const char *str, int ch); // 문자열에서부분문자열이존재하는지검색하는함수 char *strstr (const char *str, const char *sub_str); 주어진문자열에서문자 ( 또는문자열 ) 가있다면검색된위치 ( 주소 ) 를반환 존재하지않는문자이면널포인터 (NULL) 를반환 strchr : 문자열의처음부터처음으로일치하는문자를검색 strrchr : 문자열의끝에서부터일치하는문자를검색 32

문자열관련유틸리티함수 숫자를문자열로변환하는함수 정수형숫자를 2진수, 8진수, 10진수또는 16진수의문자열로변환 itoa 함수 : integer to ascii ltoa 함수 : long to ascii #include <stdlib.h> // int 형숫자를문자열 str 로변환 char *itoa (int value, char *str, int radix); // long 형숫자를문자열 str 로변환 char *ltoa (long value, char *str, int radix); 33

문자열관련유틸리티함수 (cont d) 문자열을숫자로변환하는함수 문자열을숫자로 ( 실수형또는정수형 ) 변환 #include <stdlib.h> // 문자열 str 을 double 형실수로변환 double atof (const char *str); // 문자열 str 을 int 형정수로변환 int atoi (const char *str); // 문자열 s 을 long 형정수로변환 long atol (const char *str); 34

구조체의선언및초기화 구조체초기화의규칙 유도형 초기값은중괄호를사용하며콤마로분리 ( 구조체에정의된형식과일치 ) typedef struct _score char name[12]; int kor, eng, math, tot; float ave; SCORE; SCORE a = 서두옥, 70, 80, 90, 240, 80.0; a 서두옥 70 80 90 240 80.0 a.name a.kor a.eng a.math a.tot a.ave 35

유도형 (cont d) 구조체배열 typedef struct _score char name[12]; int kor, eng, math, tot; float ave; SCORE; SCORE arr[3]; arr[0] arr[1] arr[2] 서두옥 70 80 90 240 80.0 홍길동 70 60 80 210 70.0 서하은 90 80 100 270 90.0 arr 36

중첩구조체 typedef struct struct int year; int month; int day; date; struct int hour; int min; int sec; time; STAMP; 유도형 (cont d) 추천하지않는방식 d) 선호하는방식 typedef struct int year; int month; int day; DATE; typedef struct int hour; int min; int sec; TIME; typedef struct DATE date; TIME time; STAMP; STAMP stamp; STAMP stamp; 37

유도형 (cont d) 간접표기법 (Indirection notation) a. name (*p). name typedef struct _score SCORE; char int float name[12]; kor, eng, math, tot; ave; SCORE a; SCORE *p = &a; p a (*p).eng (*p).tot (*p).name (*p).kor (*p).math (*p).ave 서두옥 70 80 90 240 80.0 a.name a.kor a.eng a.math a.tot a.ave 38

유도형 (cont d) 선택표기법 (Selection notation) a. name p -> name typedef struct _score SCORE; char int float name[12]; kor, eng, math, tot; ave; SCORE a; SCORE *p = &a; p a p->eng p->tot p->name p->kor p->math p->ave 서두옥 70 80 90 240 80.0 a.name a.kor a.eng a.math a.tot a.ave 39

유도형 (cont d) 프로그램예제 : 개별멤버전달 (1/2) #include <stdio.h> typedef struct _score char name[12]; int kor, eng, math, tot; float ave; SCORE; int float SUM(int, int, int); AVE(int, int, int); int main(void) SCORE a; printf(" 학생성적을입력하시오... \n"); printf(" 학생이름 : "); gets(a.name); printf(" 국어점수 : "); scanf("%d", &a.kor); printf(" 영어점수 : "); scanf("%d", &a.eng); printf(" 수학점수 : "); scanf("%d", &a.math); 40

유도형 (cont d) 프로그램예제 : 개별멤버전달 (2/2) a.tot = SUM(a.kor, a.eng, a.math); a.ave = AVE(a.kor, a.eng, a.math); printf("\n\t ### 입력정보 ### \n\n"); printf("%10s, %3d, %3d, %3d, %5d, %8.2f \n", a.name, a.kor, a.eng, a.math, a.tot, a.ave); ave); return 0; int SUM(int a, int b, int c) return a + b + c; 서두옥 70 80 90?????? a.kor a.eng a.math a.tot a.ave float AVE(int a, int b, int c) return (float)(a + b + c)/3; 70 80 90 a b c 41

유도형 (cont d) 프로그램예제 : 전체구조체전달 (1/2) #include <stdio.h> typedef struct _score char name[12]; int kor, eng, math, tot; float ave; SCORE; SCORE void INPUT(void); OUTPUT(SCORE); int main() SCORE a; a 서두옥 70 80 90 240 80.00 a = INPUT(); OUTPUT(a); return 0; temp temp = a; 서두옥 70 80 90 240 80.00 42

유도형 (cont d) 프로그램예제 : 전체구조체전달 (2/2) SCORE INPUT(void) SCORE temp; printf(" 학생성적을입력하시오... \n\n"); printf(" 학생이름 : "); gets(temp.name); printf(" 국어점수 : "); scanf("%d", &temp.kor); printf(" 영어점수 : "); scanf("%d", &temp.eng); printf(" 수학점수 : "); scanf("%d", &temp.math); temp.tot = temp.kor + temp.eng + temp.math; temp.ave = (float)temp.tot / 3; void return temp; OUTPUT(SCORE temp) printf("\n\t ### 입력정보 ### \n\n"); printf("%10s, %3d, %3d, %3d, %5d, %8.2f \n", temp.name, temp.kor, temp.eng, temp.math, temp.tot, temp.ave); return; 43

유도형 (cont d) 프로그램예제 : 포인터를이용한구조체전달 (1/2) #include <stdio.h> typedef struct _score char name[12]; int kor, eng, math, tot; float ave; SCORE; void INPUT(SCORE *); void OUTPUT(SCORE *); int main() SCORE a; a 서두옥 70 80 90 240 80.00 INPUT(&a); OUTPUT(&a); SCORE *p = &a; return 0; p 44

유도형 (cont d) 프로그램예제 : 포인터를이용한구조체전달 (2/2) void INPUT(SCORE *p) printf(" 학생성적을입력하시오... \n\n"); printf(" 학생이름 : "); gets(p->name); printf(" 국어점수 : "); scanf("%d", &p->kor); printf(" 영어점수 : "); scanf("%d", &p->eng); printf(" 수학점수 : "); scanf("%d", &p->math); p->tot = p->kor + p->eng + p->math; p->ave = (float)p->tot / 3; void return; OUTPUT(SCORE *p) printf("\n\t ### 입력정보 ### \n\n"); printf("%10s, %3d, %3d, %3d, %5d, %8.2f \n", p->name, p->kor, p->eng, p->math, p->tot, p->ave); return; 45

공용체의개념 유도형 (cont d) 메모리에서서로다른데이터형식을공유할수있는개념 공용체는구조형과같은문법양식을따른다. struct 키워드대신 union 를쓰는것외에는모두똑같다. 공용체를참조하는규칙은구조형을참조하는것과동일하다. typedef union char ch; int i; double d; TYPE; 1000 1001 1002 1003 1004 1005 1006 1007 TYPE temp; temp.ch temp.i temp.d 46

열거형의개념 정수형에기반 유도형 (cont d) 열거형에서각정수값은열거상수라고불리는식별자 목적 : 정수에이름을할당하는것 // 열거화된변수형 enum 열거형상수,. 변수식별자 ; // 열거화된태그형 enum tag 열거형상수, ; enum tag 변수식별자 ; 47

전처리 #define #define MAX_SIZE 1024 preprocessing (macro expansion) #define MAX_SIZE 1024 #define ADD(a, b) ((a) + (b)) #define ADD(a, b) ((a) + (b)) int main(void) int main(void) char str[max_size]; char str[1024]; int res; int res; res = ADD(10, 20); res = 10 + 20; return 0; return 0; 48

전처리 (cont d) 조건컴파일 (conditional compile) 특정조건을만족할경우에지정한범위내의문장을컴파일 조건컴파일지시자사용형식 를사용하지않기때문에 #endif 생략불가 ++, --, &, * 와기타복합연산자사용제한 #ifdef 와 #ifndef 는 #if defined( 매크로명 ), #if!defined( 매크로명 ) #if 상수식1 #ifdef 매크로명 #ifndef 매크로명 실행문장영역1 #elif 상수식2 실행문장영역2 #else 실행문장영역1 #elif 상수식1 실행문장영역2 #else 실행문장영역1 #elif 상수식1 실행문장영역2 #else 실행문장영역n #endif 실행문장영역n #endif 실행문장영역n #endif 49

전처리 (cont d) 분할컴파일 #ifndef MAX_SIZE #define MAX_SIZE 3 #endif #ifndef f SCORE_H_ #define SCORE_H_ typedef struct _score char int float SCORE; name[10]; kor, eng, math, tot; ave; score.h extern void INPUT(SCORE *); extern void OUTPUT(SCORE *); #endif #include <stdio.h> #include "score.h" #include <stdio.h> #include "score.h" int main()... void INPUT(SCORE *p)... void OUTPUT(SCORE *p)... main.c score.c 링킹 main.obj + score.obj Clickseo.exe 50

포인터에대한포인터 포인터응용 ppa pa a 0x0012FF70 0x0012FF7C 10 0x0012FF64 0x0012FF70 0x0012FF7C int a; int *pa; int **pa; a = 10; pa = &a; ppa = &pa; printf( %3d, a); printf( %3d, *pa); printf( %3d, **ppa); 51

포인터응용 (cont d) 포인터배열 #include <stdio.h> int main() arr[0] arr[1] arr 10 a 20 b int a = 10, b = 20, c = 30; int *arr[3]; arr[2] 30 c arr[0] = &a; arr[1] = &b; arr[2] = &c; printf("a : %d, b : %d, c : %d \n", *arr[0], *arr[1], *arr[2] ); return 0; 52

함수포인터 포인터응용 (cont d) 함수를가리킬수있는포인터 자주사용되는함수의주소를배열에저장해두고호출하면속도가빨라진다. 잘쓰이지는않지만, 수치해석이나그래픽같은분야에서사용 #include <stdio.h> int ADD(int, int); int main() int a = 10, b = 20, sum = 0; int (*p)(int, int) = ADD; sum = p(a, b); printf("%d + %d = %d \n", a, b, sum); return 0; int ADD(int a, int b) return a + b; 53

포인터응용 (cont d) 2 차원배열 : 1 차원배열의배열 2 차원배열의논리적인구조 int table[3][5]; table table[0] [0] 0 1 2 3 4 table[1] [1] 10 11 12 13 14 table[i][j]; table[2] [2] 20 21 22 23 24 [0] [1] [2] [3] [4] 54

포인터응용 (cont d) 2 차원배열과포인터 table[i][j] == *(*(table+i)+j) table table + 0 == &table[0] table[0] 0 1 2 3 4 table + 1 == &table[1] table[1] 10 11 12 13 14 table + 2 == &table[2] table[2] 20 21 22 23 24 배열이름은첫번째배열원소의시작주소값을갖는포인터상수 table == &table[0] table[0] == &table[0][0] ] 55

포인터응용 (cont d) 한행씩전달 table[row] void PRINT (int arr[]) int i; 0 1 2 3 10 11 12 13 20 21 22 23 30 31 32 33 40 41 42 43 table arr for (i = 0; i < COL; i++) printf( %3d, arr[i] ); printf( \n ); #include <stdio.h> #define ROW 5 #define COL 4 void PRINT (int []); int main(void) int row; int table[row][col] = 00, 01, 02, 03, 10, 11, 12, 13, 20, 21, 22, 23, 30, 31, 32, 33, 40, 41, 42, 43 ; for (row = 0; row < ROW; row++) PRINT (table[row]); return; return 0; 56

포인터응용 (cont d) 전체배열전달 table void PRINT (int p[][col]) int i, j; 00 01 02 03 10 11 12 13 20 21 22 23 30 31 32 33 40 41 42 43 table for (i = 0; i < ROW; i++) for (j = 0; j < COL; j++) printf( %3d, p[i][j] ); printf( \n ); return; p #include <stdio.h> #define ROW 5 #define COL 4 void PRINT (int [][COL]); int main(void) int table[row][col] = 00, 01, 02, 03, 10, 11, 12, 13, 20, 21, 22, 23, 30, 31, 32, 33, 40, 41, 42, 43 ; PRINT(table); return 0; 57

메모리할당 : malloc 포인터응용 (cont d) malloc 함수는매개변수로필요한메모리의바이트의수를가지며, 그 바이트수를수용할수있는크기의메모리블록을할당한다. 할당된메모리의첫번째바이트를 void 포인터로되돌린다. 할당된메모리는초기화되어있지않다 ( 쓰레기값 ). void * malloc(size_t size); int *p = NULL; p = (int *) malloc(sizeof (int) ) if (p == NULL) printf( 메모리할당실패!!! n ); exit(100); 4 bytes p 58

인접메모리할당 : calloc 포인터응용 (cont d) 일반적으로배열을위한메모리할당에주로쓰인다. 특정크기의요소들을배열로담을수있을만큼연속적인메모리블록을할당 할당된배열의첫번째요소를가리키는포인터를반환 할당된메모리를초기화 ( 즉, 할당된메모리의를 0 으로초기화 ) void * calloc(size_t element-count, size_t element-size); int *p = NULL; p = (int *) calloc(200, sizeof (int) ) if (p == NULL) printf( 메모리할당실패!!! n ); exit(100); p... 800 bytes 59

메모리재할당 : realloc 메모리재할당에쓰인다. 포인터응용 (cont d) void * realloc(void *p, size_t new_size); p 18 55 33 12 64 1 90 31 5 77 10 integers p p = (int *)realloc(p, 15 * sizeof(int)); 18 55 33 12 64 1 90 31 5 77????? 15 integers 60

메모리해제 : free 포인터응용 (cont d) malloc, calloc, realloc에의해할당된메모리가더이상필요없을때는 free 함수를사용하여해제한다. 프로그램의종료시에는메모리를반드시지울필요는없다. 이때는운영체제가모든메모리를해제한다. p p 4 bytes 4 bytes free (p) ; p... 800 bytes free (p) ; p... 800 bytes 61

명령행인자 포인터응용 (cont d) int main(int argc, char *argv[], char **env) int main(int argc, char **argv, char **env) argc : 명령행인자의개수 **argv : 명령행인자 ( 문자열 ) 가있는메모리의시작주소 **env : 현재시스템에설정되어있는환경변수 argc 3 C: > mycopy test.txt copy.txt argv[0] argv[1] argv[2] argv m y c o p y. e x e \0 t e s t. t x t \0 ag argv[3] NULL c o p y. t x t \0 62

명령행인자 (cont d) 포인터응용 (cont d) **env : 현재시스템에설정되어있는환경출력 #include <stdio.h> void main(int argc, char **argv, char **env) for( ; *env; env++) puts(*env); env[0] env[1]... env[n] env NULL ALLUSERPROFILE=C: Documents and Setting All Users APPDATA=C: Documents and Settings 서두옥 Application Data _MSDEV_BLD_ENV_=1 63

참고문헌 [1] 서두옥, 이동호 ( 감수 ), 또하나의 C : 프로그래밍은셀프입니다, 프리렉, 2011. [2] 서현우, 뇌를자극하는 C 프로그래밍, 한빛미디어, 2005. [3] 윤성우, 열혈강의 C 프로그래밍, 프리렉, 2006. [4] 정재은, 다시체계적으로배우는 C 언어포인터, 정보문화사. [5] 김일광, C 프로그래밍입문 : 프로그래밍을모국어처럼유창하게, 한빛미디어, 2004. [6] Behrouz A. Forouzan, Richard F. Gilberg, 김진외 7 인공역, 구조적프로그래밍기법을위한 C, 도서출판 인터비젼, 2004. [7] Brian W. Kernighan, Dennis M. Ritchie, 김석환외 2인공역, The C Programming Language : 2/e, 대영사, 2004. [8] SAMUEL P. HARBISON Ⅲ, GUY L. STEELE, C 프로그래밍언어 : C : A Reference Manual, Pearson Education Korea. [8] Wikipedia, http://www.wikipedia.org/. 이강의자료는저작권법에따라보호받는저작물이므로무단전제와무단복제를금지하며, 내용의전부또는일부를이용하려면반드시저작권자의서면동의를받아야합니다. Copyright Clickseo.com. All rights reserved. 64