자료구조
자료구조 제 4강
한 면만 쓴 종이
2022. 1. 24. 23:25
전역변수(global variable)
- Data section이라고 부르는 메모리 영역에 위치한다.
지역변수 (local variable)
- 스택(stack)이라고 부르는 영역에 위치한다.
동적 메모리 할당 (dynamic memory allocation)
- 아무때나 malloc등의 함수를 호출하여 필요한 크기의 메모리를 할당할 수 있다.
- 동적으로 할당된 메모리는 힙(heap)이라고 부르는 영역에 위치한다.
- 동적으로 할당된 메모리는 명시적으로 free()함수를 호출하여 반환하지 않는 한 계속 유지된다.
전화번호부v1.0
/*
* 2022-01-24
* 전화번호부v1.0
*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define CAPACITY 100
#define BUFFER_SIZE 100
char* names[CAPACITY]; //names
char* numbers[CAPACITY]; //phone numbers
int n = 0; //number of people in phone directory
void add();
void find();
void status();
void remover();
int main() {
char command[BUFFER_SIZE];
while (1) {
printf("$ ");
scanf("%s", command);
if (strcmp(command, "add") == 0)
add();
else if (strcmp(command, "find") == 0)
find();
else if (strcmp(command, "delete") == 0)
remover();
else if (strcmp(command, "exit") == 0)
break;
}
return 0;
}
void add() {
char buf1[BUFFER_SIZE], buf2[BUFFER_SIZE];
scanf("%s", buf1);
scanf("%s", buf2);
names[n] = _strdup(buf1); //strdup 사용 이유: buf1은 스택에 할당된 메모리이므로 add함수가 return되고 나면 소멸되기 때문에 names에 복제함.
numbers[n] = _strdup(buf2);
n++;
printf("%s was added successfully.\n", buf1);
}
void find() {
char buf[BUFFER_SIZE];
scanf("%s", buf);
int i;
for (i = 0; i < n; i++) {
if (strcmp(buf, names[i]) == 0) {
printf("%s\n", numbers[i]);
return;
}
}
printf("No person named '%s' exists.\n", buf);
}
void status() {
int i;
for (i = 0; i < n; i++)
printf("%s %s\n", names[i], numbers[i]);
printf("Total %d persons.\n", n);
}
void remover() {
char buf[BUFFER_SIZE];
scanf("%s", buf);
int i;
for (i = 0; i < n; i++) {
if (strcmp(buf, names[i]) == 0) {
names[i] = names[n - 1]; //맨 마지막 사람을 삭제된 자리로 옮긴다.
numbers[i] = numbers[n - 1];
n--;
printf("'%s' was deleted successfully.\n", buf);
return;
}
}
printf("No person named '%s' exists.\n", buf);
}