티스토리 뷰
동적메모리와 연결리스트
1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #include <stdio.h> #include <stdlib.h> void insert_arr(int *arr, int size) { for (int i = 0; i < size; i++) { printf("%d 번째 양의 정수를 입력하시오 : ", i + 1); scanf("%d", (arr + i)); } } void sum_arr(int *arr, int size) { int sum = 0; for (int i = 0; i < size; i++) { sum += *(arr + i); } printf("합은 %d입니다.", sum); } int main() { int arr_size; int *arr_target; printf("정수의 갯수 : "); scanf("%d", &arr_size); arr_target = (int *)malloc(arr_size * sizeof(int)); insert_arr(arr_target, arr_size); sum_arr(arr_target, arr_size); free(arr_target); return 0; } | cs |
2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | #include <stdio.h> #include <stdlib.h> #define STR_SIZE 100 int main() { char **A = NULL; // char A[][]를 가르키는 문자열 배열 포인터 int arr_size; printf("문자열의 개수 : "); scanf("%d", &arr_size); if ((A = malloc(arr_size * sizeof(int))) != NULL) { // int ** = (int *)malloc(sizeof(char *)) // for (int i = 0; i < arr_size; i++) { A[i] = (char *)malloc(STR_SIZE); } printf("%d개의 문자열을 지정할 수 있는 공간이 할당되었습니다.\n", arr_size); } A[0] = "Think like a man of action and act like man of thought."; A[1] = "Courage is very important.Like a muscle, it is strengthened by use."; A[2] = "Life is the art of drawing sufficient conclusions from insufficient premises."; A[3] = "By doubting we come at the truth."; A[4] = "A man that hath no virtue in himself, ever envieth virtue in others."; A[5] = "When money speaks, the truth keeps silent."; A[6] = "Better the last smile than the first laughter."; A[7] = "In the morning of life, work; in the midday, give counsel; in the evening, pray."; A[8] = "Painless poverty is better than embittered wealth."; A[9] = "A poet is the painter of the soul."; for (int i = 0; i < arr_size; i++) { printf("원소의 데이터 크기 : %d, 내용 : %s\n", sizeof(A[i]), (char *)A[i]); } free(A); printf("%d\n", sizeof(A)); // 0xddddddd는 NULL 값을 의미 하지만 NULL 또한 4바이트를 가짐 return 0; } | cs |
3.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | #include <stdio.h> #include <stdlib.h> #include <string.h> // strcpy() 등 문자열 처리함수 사용하기 위한 라이브러리 #define NAME_SIZE 12 #define PHONE_SIZE 28 typedef struct book { char *name; char *phone; } BOOK; int main() { BOOK *A; // BOOK 배열 포인터 생성 int arr_size; printf("주소의 개수 : "); scanf("%d", &arr_size); while (getchar() != '\n'); // fflush(stdin)이 동작하지 않아 이렇게 처리, getchar() 한 개의 문자를 입력받음 // getchar()을 계속 읽어들여 처음나오는 \n을 찾아 그 다음 문장을 넘김, 엔터 전까지면 모든 버퍼를 비워낼 수 있다. if ((A = malloc(arr_size * sizeof(BOOK))) != NULL) { // int ** = (int *)malloc(sizeof(char *)) for (int i = 0; i < arr_size; i++) { (A + i)->name = (char *)malloc(NAME_SIZE); (A + i)->phone = (char *)malloc(PHONE_SIZE); } printf("%d개의 주소를 저장할 수 있는 공간이 할당되었습니다.\n", arr_size); } for (int i = 0; i < arr_size; i++) { char buffer_name[NAME_SIZE]; char buffer_phone[PHONE_SIZE]; printf("이름을 입력하시오 : "); gets_s(buffer_name, sizeof(buffer_name)); strcpy((A + i)->name, buffer_name); printf("휴대폰번호를 입력하시오 : "); gets_s(buffer_phone, sizeof(buffer_phone)); strcpy((A + i)->phone, buffer_phone); } for (int i = 0; i < arr_size; i++) { printf("이름 : %s\n", (A + i)->name); printf("번호 : %s\n", (A + i)->phone); } free(A); return 0; } | cs |
4.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #include <stdio.h> #include <stdlib.h> #include <string.h> // strlen()함수 사용을 위한 라이브러리 호출 #define MAX_LENGTH 50 char *get_word() { char *flash; char buffer[MAX_LENGTH]; printf("단어를 입력하시오 : "); gets_s(buffer, sizeof(buffer)); int str_size = sizeof(char)*strlen(buffer); flash = (char *)malloc(str_size + 1); // 마지막에 NULL문자로 문자열 끝 알려주기, 안하면 free()에서 에러발생 strcpy(flash, buffer); return flash; }; int main() { char *check; check = get_word(); printf("동적 메모리에 저장된 단어는 %s입니다.\n", check); free(check); return 0; } | cs |
5.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | #include <stdio.h> #include <stdlib.h> typedef struct LIST { int num; struct LIST *link; } LIST; LIST *add_list(LIST **list, LIST **prev, int input); // 데이터 추가 void read_list(LIST **lsit, LIST **next); // 데이터 참조 void delete_list(LIST **list, LIST **next); // 메모리 해제 int main() { LIST *list = NULL; LIST *prev = NULL; LIST *next = NULL; int input; do { printf("양의 정수를 입력하세요(종료: -1) : "); scanf("%d", &input); if (input == -1) { break; } add_list(&list, &prev, input); //while (getchar() != '\n'); // 버퍼 비우기, fflush 먹통일 때 사용 } while (1); read_list(&list, &next); // 데이터 참조 delete_list(&list, &next); // 메모리 해제 return 0; } LIST *add_list(LIST **list, LIST **prev, int input) { LIST *data; // data는 새로 추가할 데이터 data = (LIST*)malloc(sizeof(LIST)); // 동적메모리 할당 data->num = input; if (*list == NULL) { // list가 초기값이면, *list = data; // list가 가리키는 주소에 data를 대입, list는 처음 데이터 } else { // list에 값이 있으면, (*prev)->link = data; // prev.link에 현주소 대입 } data->link = NULL; // 마지막에 해당하므로 NULL *prev = data; } void read_list(LIST **list, LIST **next) { // 데이터 참조 LIST *data; data = *list; // 처음을 가져옴 while (data != NULL) { // 끝은 항상 NULL printf("%d->", data->num); *next = data->link; // 다음 참조를 넘김 data = *next; } printf("NULL\n"); next = NULL; } void delete_list(LIST **list, LIST **next) { // 메모리 해제 LIST *data; data = *list; while (data != NULL) // 초기화와 동일 { *next = data->link; free(data); data = *next; } } | cs |
6.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | #include <stdio.h> #include <stdlib.h> #include <string.h> #include <Windows.h> #define SIZE 30 typedef struct LIST { char name[SIZE]; char phone[SIZE]; struct LIST *link; } LIST; int view_list(void); // 메뉴 선택 void clear_list(LIST **list, LIST **next); // 1. 초기화 void add_list(LIST **list, LIST **prev); // 2. 전화 번호 추가 void search_list(LIST **next, LIST **list); // 3. 전화 번호 탐색 void delete_list(LIST **next, LIST **list); // 메모리 해제 int main() { LIST *info = NULL; LIST *prev = NULL; LIST *next = NULL; int insert = 0; while ((insert = view_list()) != 4) // 4. 종료 { while (getchar() != '\n'); // 버퍼 비우기, fflush 먹통일 때 사용 system("cls"); if (insert == 1) { // 1. 초기화 clear_list(&info, &next); } else if (insert == 2) { // 2. 전화 번호 추가 add_list(&info, &prev); } else if (insert == 3) { // 3. 전화 번호 탐색 search_list(&next, &info); } else { // 예외 처리 } } delete_list(&next, &info); // 메모리 해제 return 0; } int view_list(void) { int choice = 0; printf("연결 리스트를 이용한 전화 번호부 메뉴\n"); printf("----------------------------------\n"); printf("1. 초기화\n"); printf("2. 전화 번호 추가\n"); printf("3. 전화 번호 탐색\n"); printf("4. 종료\n"); printf("----------------------------------\n"); printf("번호를 입력하세요 : "); scanf("%d", &choice); return choice; } void clear_list(LIST **list, LIST **next) { // 1. 초기화 printf("1. 초기화\n"); LIST *data; data = *list; // p는 list를 가지고 있음 while (data != NULL) { // 리스트가 비어있지 않으면, *next = data->link; // next에 다음 주소 저장 free(data); // 현재 주소 삭제 data = *next; // p는 다음 데이터를 참조 } next = NULL; printf("초기화가 완료되었습니다.\n"); Sleep(1000); system("cls"); } void add_list(LIST **list, LIST **prev) { // 2. 전화 번호 추가 printf("2. 전화번호부 추가\n"); LIST *data; // p는 새로 추가할 데이터 data = (LIST*)malloc(sizeof(LIST)); // 동적메모리 할당 printf("이름: "); gets_s(data->name, sizeof(char)*SIZE); printf("번호: "); gets_s(data->phone, sizeof(char)*SIZE); if (*list == NULL) { // list가 초기값이면, *list = data; // list가 가리키는 주소에 p를 대입, list는 처음 데이터 } else { // list에 값이 있으면, (*prev)->link = data; // prev.link에 현주소 대입 } data->link = NULL; // 마지막에 해당하므로 NULL *prev = data; system("cls"); } void search_list(LIST **next, LIST **list) { // 3. 전화 번호 탐색 printf("3. 전화 번호 탐색\n"); LIST *data; // 순차검색 매개값 char input[SIZE]; printf("찾을 이름: "); gets_s(input, sizeof(char)*SIZE); data = *list; // 처음을 가져옴 while (data != NULL) { // 끝은 항상 NULL if (!(strcmp(data->name, input))) { printf("전화 번호는 %s입니다.\n", data->phone); } *next = data->link; data = *next; } printf("검색을 마쳤습니다.(3초간 확인)\n"); Sleep(3000); system("cls"); next = NULL; } void delete_list(LIST **next, LIST **list) { // 메모리 해제 LIST *data; data = *list; while (data != NULL) // 초기화와 동일 { *next = data->link; free(data); data = *next; } } | cs |
7.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | #include <stdio.h> #include <stdlib.h> #include <string.h> #include <Windows.h> #define TITLE_SIZE 100 typedef struct MOVIE { char title[TITLE_SIZE]; int premiere; struct MOVIE *link; } MOVIE; int view_movie(void); // 메뉴 선택 void add_movie(MOVIE **list, MOVIE **prev); // 1. 영화 정보 추가 void list_moive(MOVIE **next, MOVIE **list); // 2. 영화 정보 출력 void delete_movie(MOVIE **next, MOVIE **list); // 메모리 해제 int main() { MOVIE *movie = NULL; MOVIE *prev = NULL; // 연결리스트의 생성에는 '이전' 단계의 링크 값을 바꾸는 과정이 포함된다. MOVIE *next = NULL; // 연결리스트이 순차실행에는 '현'주소를 지우기 전, '다음' 값을 저장해야 한다. int choice = 0; while ((choice = view_movie()) != 3) // 3. 종료 { while (getchar() != '\n'); // 버퍼 비우기, fflush 먹통일 때 사용 system("cls"); if (choice == 1) { // 1. 영화 정보 추가 add_movie(&movie, &prev); } else if (choice == 2) { // 2. 영화 정보 출력 list_moive(&next, &movie); } else { // 예외 처리 } } delete_movie(&next, &movie); // 메모리 해제 return 0; } int view_movie(void) { int choice = 0; printf("연결 리스트를 이용한 전화 번호부 메뉴\n"); printf("----------------------------------\n"); printf("1. 영화 정보 추가\n"); printf("2. 영화 정보 출력\n"); printf("3. 종료\n"); printf("----------------------------------\n"); printf("번호를 선택하시오 : "); scanf("%d", &choice); return choice; } void add_movie(MOVIE **list, MOVIE **prev) { // 1. 영화 정보 추가 printf("1. 영화 정보 추가\n"); MOVIE *data; // data는 새로 추가할 데이터 data = (MOVIE*)malloc(sizeof(MOVIE)); // 동적메모리 할당 printf("영화의 제목을 입력하시오: "); gets_s(data->title, sizeof(char)*TITLE_SIZE); printf("영화의 개봉 연도를 입력하시오: "); scanf("%d", &data->premiere); if (*list == NULL) { // list가 초기상태면, *list = data; // list가 가리키는 주소에 data에 대입, list는 처음 데이터 } else { // list에 값이 있으면, (*prev)->link = data; // prev.link에 현주소 대입 } data->link = NULL; // 마지막에 해당하므로 NULL *prev = data; system("cls"); } void list_moive(MOVIE **next, MOVIE **list) { // 2. 영화 정보 출력 printf("2. 영화 정보 출력\n"); MOVIE *data; data = *list; // 처음을 가져옴 while (data != NULL) { // 끝은 항상 NULL printf("제목 : %s\n", data->title); printf("개봉 연도 : %d\n", data->premiere); *next = data->link; // 다음 참조를 넘김 data = *next; } printf("검색을 마쳤습니다.(3초간 확인)\n"); Sleep(3000); system("cls"); next = NULL; } void delete_movie(MOVIE **next, MOVIE **list) { // 메모리 해제 MOVIE *data; data = *list; while (data != NULL) { *next = data->link; free(data); data = *next; } } | cs |
'프로그래밍 > C' 카테고리의 다른 글
[자료구조] 3일차_과제(180323) - 연결리스트 (0) | 2018.03.30 |
---|---|
[자료구조] 4일차_과제(180323) - 재귀함수 (0) | 2018.03.30 |
[창의적it 프로그래밍] 1차 과제 -포인터- (0) | 2018.03.16 |
[자료구조] 2일차_과제(180316) - 오목 (0) | 2018.03.16 |
[창의적it 프로그래밍] 1차 과제 -구조체- (0) | 2018.03.13 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- Next.js
- gcp
- vue.js
- oracle
- RDBMS
- aws
- REACT
- node.js
- vue
- SQLite
- PostgreSQL
- DevOps
- Remix
- MySQL
- Gatsby.js
- 이진탐색 #중복
- hoisting
- nuxt.js
- JavaScript
- svelte
- alpine.js
- Cloud
- nosql
- Quasar
- Angular
- Azure
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함