#include <stdio.h>
#include <string.h>
#define CAPACITY 100
#define BUFFER_SIZE 20
char* names[CAPACITY]; // 배열의 각 칸에 저장되는 데이터의 타입. 사람 이름의 주소를 저장하는 배열 = char*
char* numbers[CAPACITY]; // 전화번호는 그냥 '010-1234-5678'같이 문자열로 다루는 게 편함
int n = 0; // 저장되는 사람의 수.
void add();
void find();
void status();
void remove();
int main()
{
char command[BUFFER_SIZE];
while (1) // 사용자가 빠져나가기 전까지 무한반복
{
printf("$ ");
scanf("%s", command); // 사용자로부터 명령어를 받음
if (strcmp(command, "add") == 0) // 명령어와 두 문자열을 비교. 두 문자열이 동일하면 0를 리턴
add();
else if (strcmp(command, "find"))
find();
else if (strcmp(command, "status"))
status();
else if (strcmp(command, "remove"))
remove();
else if (strcmp(command, "exit"))
break;
}
return 0;
}
void add()
{
char buf1[BUFFER_SIZE], buf2[BUFFER_SIZE]; // 이름과 번호 모두 20글자를 넘지 않음
scanf("%s", buf1); // buf1, 2는 지역변수이기 때문이 함수의 스코프를 벗어나면 사라짐.
scanf("%s", buf2);
names[n] = strdup(buf1); // names에는 배열의 주소를 저장해야 함
numbers[n] = strdup(buf2); // strdup는 배열을 만들고 매개변수로 받은 하나의 문자열을 복사하여 생성하고 동적 할당 받은 배열의 주소를 반환. deep copy.
n++;
printf("%s was added successfully.\n", buf1);
}
/*
char* strdup(char *s) // string duplication
{
char* p;
p = (char*)malloc(strlen(s)+1); // strlen은 딱 글자수만 반환. 때문에 null문자를 저장할 공간+1
if(p!=NULL) // 동적 할당이 성공적으로 이뤄졌음.
strcpy(p, s); // s에 있는 배열을 p로 복사
return p; // 함수가 종료되면서 buf1, 2는 사라지더라도 p는 heap에 동적할당을 받았기 때문에 삭제x
}
*/
/* 복습 time
1. 전역 변수(global variable): 함수 외부에 존재. Data section 메모리 영역에 위치
2. 지역 변수(local variable): 함수 내부에 존재. stack 영역에 존재.
3. 동적 메모리 할당(dynamic memory allocation): heap 영역에 존재. free()를 통해 반환해야함.
데이터 섹션은 프로그램이 진행되는 동안 거의 변하지 않음.
스택은 FILO. 가장 늦게 생성된 메모리가 가장 먼저 소멸.
void find()
{
char buf1[BUFFER_SIZE];
scanf_s("%s", buf1);
for (int i = 0; i < n; i++)
{
if (strcmp(buf1, names[i])==0) // 입력받은 이름과 배열에 저장된 이름을 전부 한 번씩 비교하며 확인
{
printf("%s", numbers[i]);
return; // 이름을 찾으면 함수를 빠져나감
}
}
printf("No Person named '%s' existes. \n", buf1); // for문을 다 돌았지만 매칭되는 이름을 찾지 못함
}
void status()
{
for (int i = 0; i < n; i++)
{
printf("%s %s\n", names[i], numbers[i]);
}
printf("Total %d people.\n", n);
}
void remove()
{
char buf1[BUFFER_SIZE];
scanf_s("%s", buf1);
for (int i = 0; i < n; i++)
{
if (strcmp(buf1, names[i])==0)
{
names[i] = names[n - 1]; // 전화번호부에서 순서의 의미가 크지 않음
numbers[i] = numbers[n - 1]; // 그렇기 때문에 삭제된 자리에 맨 마지막 배열을 대체
n--;
printf("%s was deleted succesfullly.\n", buf1);
return;
}
}
printf("No person named %s exists.\n", buf1);
}
'Information Technology > C' 카테고리의 다른 글
[C언어] 전화번호부 v.4 (0) | 2020.01.07 |
---|---|
[C언어] 전화번호부 v.3 (0) | 2020.01.06 |
[C언어] 전화번호부 v.2 (0) | 2020.01.06 |
[C언어] 문자열(2) (0) | 2020.01.05 |
[C언어] 문자열(1) (0) | 2020.01.03 |