모든 C 프로그램은 main에서 시작합니다. #include <stdio.h>는 헤더 파일을 포함하여 printf를 사용하여 출력할 수 있게 합니다. 함수는 호출할 수 있는 이름이 붙은 블록이며, \n는 새 줄을 시작합니다. main는 "성공"을 의미하는 0를 반환합니다.
#include <stdio.h>
void greet(void) {
printf("Hello, world!\n");
}
int main(void) {
greet();
printf("I am learning C.\n");
return 0;
}
모든 C 프로그램은 헤더를 포함한 후 main에서 시작됩니다
1.2
변수, 타입 & 산술 연산
C는 모든 변수에 대해 유형이 필요합니다: int (정수), double (부동소수점), char (단일 문자). printf은 각 값에 대해 포맷 지정자 — %d, %f, %c — 를 사용합니다. 두 정수 사이의 /는 정수 나누기이며, %는 나머지의 나머지입니다.
#include <stdio.h>
int main(void) {
int n = 17;
double pi = 3.14;
char grade = 'A';
printf("%d %.2f %c\n", n, pi, grade); // 17 3.14 A
printf("%d %d\n", 7 / 2, 7 % 2); // 3 1
return 0;
}
포맷 스트링은 출력과 읽기 모두를 제어합니다:
Specifier
Type
Example output
%d
int
17
%f
double (%.2f = 2 소수점 자릿수)
3.14
%c
char
A
%s
문자열
Mei
%zu
크기 (sizeof / strlen에서)
3
%x
unsigned int, 진수 16로 출력
ff
scanf("%d", &n)는 주소를 통해 int을 읽습니다(&을 참고하십시오). 입력 및 출력 형식은 동일하지 않습니다: printf("%f", x)은 double을 출력하지만, scanf("%lf", &x)은 double을 읽습니다. 입력 %f에는 float *이 필요합니다. 성공적으로 할당된 항목의 반환 개수를 확인하십시오. 이 함수의 자매 함수인 sscanf은 문자열에서 값을 Parsing합니다:
#include <stdio.h>
int main(void) {
char line[] = "Mei 88";
char name[20];
int score;
if (sscanf(line, "%19s %d", name, &score) != 2) return 1;
printf("%s scored %d\n", name, score); // Mei scored 88
return 0;
}
1.3
주석 & 스타일
주석은 인간을 위한 메모이며, 컴파일러는 이를 무시합니다. 한 줄에는 //를, 블록에는 /* ... */을 사용하십시오. 적절한 indentation과 명확한 네이밍은 코드를 읽기 쉽게 만듭니다.
#include <stdio.h>
int main(void) {
// a single-line comment
/* a block
comment */
int total = 3 + 4; // clear names help
printf("%d\n", total); // 7
return 0;
}
Common mistakes
선언문과 표현 문장은 ;으로 끝납니다; 복합 블록 { ... }에는 추가 세미콜론이 필요하지 않습니다. main은 int(return 0;)를 반환해야 합니다.
printf은 포맷 문자열이 필요합니다: %d은 int용, %f은 double용이며, 새로운 줄을 위해 \n가 필요합니다.
정수 double에 대해 %d과 같은 잘못된 포맷은 정의되지 않은 행동을 유발하며, 단순히 쓰레기 데이터만 출력하는 것만은 보장되지 않습니다. 인자 타입을 일치시키십시오.
if는 조건이 참일 때 블록을 실행합니다. C는 기본적으로 진정한 부울리/type이 없습니다: 0은 false이고 0이 아닌 모든 값은 true입니다. else if와 else으로 선택을 체인할 수 있습니다. ==, !=, <, >, <=, >=과 비교하십시오.
#include <stdio.h>
int main(void) {
int score = 72;
if (score >= 90) {
printf("A\n");
} else if (score >= 60) {
printf("Pass\n");
} else {
printf("Fail\n");
}
return 0;
}
if는 참인 분기를 선택; else는 거짓 분기를 선택합니다
2.2
스위치
switch은 정수 값을 통해 하나의 case을 선택합니다. 각 case은 탈출하기 위해 break이 필요합니다. 이 없이 다음 case로 C가 'fall through'됩니다. match하는 것이 없으면 default이 실행됩니다.
#include <stdio.h>
int main(void) {
int day = 3;
switch (day) {
case 1: printf("Mon\n"); break;
case 2: printf("Tue\n"); break;
case 3: printf("Wed\n"); break;
default: printf("Other\n");
}
return 0;
}
Common mistakes
if (x = 5)는 할당하고 항상 참입니다; ==을 사용하여 비교하십시오.
각 switch 케이스에는 break;이 필요합니다. 그렇지 않으면 다음 케이스로Fall through됩니다.
함수는 매개변수(입력)를 받아 반환 값을 돌려줍니다. 반환 유형이 먼저 오고(int, double, …); void는 아무것도 반환하지 않음을 의미합니다.
#include <stdio.h>
int square(int x) { // x is a parameter
return x * x; // hand back a value
}
int main(void) {
int r = square(5);
printf("%d\n", r); // 25
return 0;
}
Parameters in; return value out
4.2
프로토타입 및 scopescope
C는 위에서 아래로 읽으므로 함수는 호출되기 전에 알려져야 합니다. 프로토타입 — 헤더 줄과 ; — 는 일찍 선언되어 main를 최상단에 두게 합니다. 변수의 scope는 그 변수가 존재하는 블록입니다: 로컬이며 블록이 끝나면 사라집니다.
#include <stdio.h>
int add(int a, int b); // prototype: declared before use
int main(void) {
printf("%d\n", add(3, 4)); // 7
return 0;
}
int add(int a, int b) { // definition comes later
int sum = a + b; // sum is local to add
return sum;
}
Common mistakes
정의되기 전에 사용되는 함수 위에는 main 위에 프로타입이 있어야 합니다.
인자는 BY VALUE로 전달됩니다 — 함수 내부의 변경 사항은 포인터를 전달하지 않는 한 caller에 영향을 주지 않습니다.
배열은 한 가지 유형의 여러 값을 저장합니다. 인덱스는 0부터 시작합니다. C는 배열의 길이를 저장하지 않으므로, 일반적인 팁인 요소 개수를 계산하는 식은 sizeof(a) / sizeof(a[0])입니다.
#include <stdio.h>
int main(void) {
int scores[3] = {88, 71, 95};
printf("%d\n", scores[0]); // 88
scores[1] = 100;
printf("%d\n", scores[1]); // 100
int n = sizeof(scores) / sizeof(scores[0]);
printf("%d\n", n); // 3
return 0;
}
Array slots are indexed from 0
5.2
배열 알고리즘
max, 총합 또는 개수를 찾기 위해 for 루프로 배열을 Traverse합니다. 항상 0부터 n - 1까지 루프합니다.
#include <stdio.h>
int main(void) {
int a[] = {3, 9, 2, 7};
int n = sizeof(a) / sizeof(a[0]);
int max = a[0], total = 0;
for (int i = 0; i < n; i++) {
if (a[i] > max) max = a[i];
total += a[i];
}
printf("%d %d\n", max, total); // 9 21
return 0;
}
5.3
2-D 배열
2-D 배열은 행과 열의 그리드입니다: grid[row][col]. 두 개의 중첩 루프를 사용하여 모든 셀을 방문합니다.
#include <stdio.h>
int main(void) {
int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
printf("%d\n", grid[1][2]); // 6
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
printf("%d ", grid[r][c]);
}
}
printf("\n"); // 1 2 3 4 5 6
return 0;
}
Common mistakes
C does NOT check array bounds: writing a[n] in a size-n array is undefined behavior.
유효한 인덱스는 0부터 n - 1까지입니다.
대부분의 식에서 배열은 첫 번째 요소에 대한 포인터로 변환되지만, 배열 자체는 포인터가 아닙니다. sizeof(a)은 실제 배열 전체의 바이트 크기를 제공합니다. 배열 매개변수는 포인터로 조정되므로, 함수는 별도의 길이 인자를 제공받아야 합니다.
포인터는 변수의 주소를 저장합니다. &x는 x의 주소를 줍니다; *p는 포인터를 Dereference — 거기에 저장된 값을 읽거나 씁니다. 포인터를 전달하면 함수가 caller의 변수를 변경할 수 있습니다(pass-by-pointer).
포인터는 주소를 저장하며, 이를 디레퍼런스하면 화살표를 따라 값에 도달함
#include <stdio.h>
void addOne(int *p) { // p holds an address
*p = *p + 1; // change the value at that address
}
int main(void) {
int x = 10;
int *ptr = &x; // & takes the address of x
printf("%d\n", *ptr); // * reads the value: 10
addOne(&x);
printf("%d\n", x); // 11 — changed through the pointer
return 0;
}
고전적인 사용 예는 Swap 함수입니다. 값만 전달하면 복사만 이루어질 뿐 — swap이 손실됩니다. 포인터를 전달하면 함수가 caller의 변수에 접근할 수 있습니다:
#include <stdio.h>
void swap_values(int a, int b) { // copies: the caller sees nothing
int t = a; a = b; b = t;
}
void swap_pointers(int *a, int *b) { // addresses: the swap is real
int t = *a; *a = *b; *b = t;
}
int main(void) {
int x = 1, y = 2;
swap_values(x, y);
printf("%d %d\n", x, y); // 1 2 (unchanged!)
swap_pointers(&x, &y);
printf("%d %d\n", x, y); // 2 1 (swapped)
return 0;
}
배열 이름은 첫 번째 요소를 가리키는 포인터 역할을 하며, 포인터 연산은 전체 요소를 단위로 이동합니다:
#include <stdio.h>
int main(void) {
int a[] = {10, 20, 30};
int *p = a; // same as &a[0]
printf("%d\n", *p); // 10
printf("%d\n", *(p + 2)); // 30 — same as a[2]
return 0;
}
NULL는 어떤 것을 가리키지 않는 포인터입니다 — Dereference하기 전에 반드시 확인하십시오.
Common mistakes
&x는 x의 주소이며; *p은 p에 저장된 값입니다.
Never use *p on an uninitialised or NULL pointer — it crashes or corrupts memory.
C string은 char의 배열입니다. 모든 string은 숨겨진 null terminator '\0'로 끝나며, 이는 어디까지 이어지는지를 표시합니다. strlen(<string.h>에서)는 그 '\0'까지의 문자를 세어줍니다. 전체 string을 %s로, 단일 문자를 %c로 출력합니다.
#include <stdio.h>
#include <string.h>
int main(void) {
char name[] = "Mei"; // 'M', 'e', 'i', '\0'
printf("%s\n", name); // Mei
printf("%zu\n", strlen(name)); // 3 (stops at '\0')
printf("%c\n", name[0]); // M
return 0;
}
C 문자열은 숨겨진 null 종결자를 끝으로 하는 char 배열입니다
'\0'에 도달할 때까지 루프하여 string을 Traverse할 수 있습니다.
#include <stdio.h>
int main(void) {
char word[] = "banana";
int count = 0;
for (int i = 0; word[i] != '\0'; i++) {
if (word[i] == 'a') count++;
}
printf("%d\n", count); // 3
return 0;
}
7.2
string.h 라이브러리
#include <string.h>는 일상적인 string 도구를 제공합니다:
함수
역할
strlen(s)
terminator을 포함하지 않는 길이
strcpy(dst, src)
복사 — dst이 충분히 커야 함
strcat(dst, src)
append src onto the end of dst
strcmp(a, b)
비교: 같으면 0, 그렇지 않으면 음수/양수
#include <stdio.h>
#include <string.h>
int main(void) {
char full[40];
strcpy(full, "Mei"); // full is now "Mei"
strcat(full, " Chen"); // append -> "Mei Chen"
printf("%s (%zu)\n", full, strlen(full)); // Mei Chen (8)
printf("%d\n", strcmp("apple", "apple") == 0); // 1 (equal)
return 0;
}
strcmp는 같으면 0을 반환하므로, 테스트는 strcmp(a, b) == 0 — 절대로 a == b가 아닙니다.
대상 배열은 결과물 또는 terminator을 위한 공간이 있어야 합니다.
Common mistakes
C 문자열은 \0 테르미네이터를 위해 한 바이트가 추가되어야 하므로, 5 글자 단어는 char[6]바이트가 필요합니다.
string을 복사하고 비교할 때는 strcpy / strcmp을 사용하고, = / ==를 사용하지 마십시오.
struct는 관련된 값들을 하나의 유형에 묶습니다. 각 값은 멤버입니다. typedef은 struct에 짧은 이름을 부여하여 Dog을 struct Dog 대신 쓸 수 있게 합니다. struct 값에는 .을 사용하되, struct 포인터에는 ->을 사용합니다.
#include <stdio.h>
typedef struct {
char name[20];
int age;
} Dog;
int main(void) {
Dog d = {"Rex", 3};
printf("%s is %d\n", d.name, d.age); // Rex is 3 (. on a value)
Dog *p = &d;
p->age = 4; // -> on a pointer
printf("%s is %d\n", d.name, d.age); // Rex is 4
return 0;
}
malloc는 실행 시간에 Heap에서 메모리를 할당하고 그에 대한 포인터를 반환합니다. realloc은 그 블록의 크기를 변경하고; free는 이를 반납합니다. 모든 malloc에는 대응하는 free가 필요하며, 그렇지 않으면 Memory leak이 발생합니다. 이들은 <stdlib.h>에 있습니다.
로컬 변수는 스택에, malloc 메모리는 free할 때까지 힙에 존재합니다
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = 3;
int *a = malloc(n * sizeof(int)); // room for 3 ints
if (a == NULL) return EXIT_FAILURE;
for (int i = 0; i < n; i++) a[i] = i * 10;
int *grown = realloc(a, 4 * sizeof *a); // positive size
if (grown == NULL) {
free(a);
return EXIT_FAILURE;
}
a = grown;
a[3] = 30;
for (int i = 0; i < 4; i++) printf("%d ", a[i]);
printf("\n"); // 0 10 20 30
free(a); // hand the memory back
return 0;
}
calloc(n, size) allocates an array like malloc AND fills it with zeros.
Common mistakes
모든 malloc에는 대응하는 free이 필요합니다; free를 누락하면 메모리 리크가 발생합니다.
free 이후 메모리를 사용하는 것은 "use-after-free"라는 중대한 버그입니다.
메모리를 사용하기 전에 malloc이 NULL을 반환하지 않았는지 확인하십시오.
양수 크기에 실패한 realloc은 NULL을 반환하고 기존 할당을 유지합니다: 단일 포인터를 교체하기 전에 임시 결과를 확인하십시오. 성공 시 작은 쪽의 바이트 수를 보존하며, 추가된 셀은 초기화되지 않습니다. 이 예시는 영크기 요청과 오버플로우를 피합니다. 일반적인 비정적 로컬 변수는 자동 저장 기간을 가지며 일반적으로 스택에 구현되지만, C는 해당 레이아웃을 요구하지는 않습니다.
linked list is a chain of nodes. Each node holds a value and a pointer to the next node; the last one points to NULL. Unlike an array it grows one node at a time with malloc. Always free every node when done.
링크드 리스트: 각 노드는 값을 가지며 다음 노드를 가리키고 NULL에서 끝납니다
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node *next;
} Node;
int main(void) {
Node *head = NULL;
for (int v = 10; v <= 30; v += 10) { // prepend 10, 20, 30
Node *n = malloc(sizeof(Node));
n->value = v;
n->next = head;
head = n;
}
for (Node *p = head; p != NULL; p = p->next) {
printf("%d ", p->value); // 30 20 10
}
printf("\n");
while (head != NULL) { // free the whole list
Node *t = head;
head = head->next;
free(t);
}
return 0;
}
10.2
스택 & 큐
스택은 LIFO(후입력 우선출력)입니다: 같은 끝에서 push와 pop을 수행합니다. 큐는 FIFO(전입력 우선출력)입니다: 뒤쪽에서 추가하고 앞쪽에서 제거합니다. 두 구조 모두 인덱스 변수가 있는 배열 위에 쉽게 구현할 수 있습니다.
#include <stdio.h>
int main(void) {
int stack[10];
int top = 0; // next free slot
stack[top++] = 1; // push
stack[top++] = 2;
stack[top++] = 3;
while (top > 0) {
printf("%d ", stack[--top]); // pop: 3 2 1
}
printf("\n");
return 0;
}
#include <stdio.h>
int main(void) {
int queue[10];
int front = 0, back = 0;
queue[back++] = 1; // enqueue
queue[back++] = 2;
queue[back++] = 3;
while (front < back) {
printf("%d ", queue[front++]); // dequeue: 1 2 3
}
printf("\n");
return 0;
}
선형 탐색은 요소를 순차적으로 확인하므로 어떤 배열에서도 작동합니다. 이진 탐색은 훨씬 빠르지만 정렬된 배열이 필요합니다: 중간 요소를 확인하고 매 단계마다 절반을 삭제합니다. 둘 다 인덱스를 반환하며, 요소가 없을 경우 -1을 반환합니다.
#include <stdio.h>
int linear(int a[], int n, int target) {
for (int i = 0; i < n; i++)
if (a[i] == target) return i;
return -1;
}
int binary(int a[], int n, int target) {
int lo = 0, hi = n - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (a[mid] == target) return mid;
else if (a[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
int main(void) {
int a[] = {2, 5, 8, 12, 16, 23};
int n = sizeof(a) / sizeof(a[0]);
printf("%d %d %d\n", linear(a, n, 12), binary(a, n, 12), binary(a, n, 9));
return 0; // 3 3 -1
}
선형 탐색은 전체 스캔; 이진 탐색은 정렬된 범위 반으로 줄임
11.2
정렬
버블 정렬은 인접한 요소를 반복 비교하여 순서가 맞지 않는 쌍을 교체합니다. 각 패스 후 가장 큰 값이 "거품처럼" 끝으로 이동합니다.
#include <stdio.h>
int main(void) {
int a[] = {5, 2, 9, 1, 7};
int n = sizeof(a) / sizeof(a[0]);
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (a[j] > a[j + 1]) {
int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
}
}
}
for (int i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n"); // 1 2 5 7 9
return 0;
}
11.3
재귀
재귀(recursion)는 함수가 자신을 호출하는 것입니다. 멈추기 위한 기본 조건(base case)이 필요하며, 그 조건으로 나아가는 재귀 호출이 필요합니다. 기본 조건이 없으면 영구히 계속됩니다.
#include <stdio.h>
int factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive call
}
int main(void) {
printf("%d\n", factorial(5)); // 120
return 0;
}
Common mistakes
이진 탐색은 정렬된 배열이 필요하며, 재귀는 기본 조건이 필요합니다.
각 재귀 호출은 기본 조건에 가까워져야 하며, 그렇지 않으면 스택 오버플로우가 발생합니다.
버블 정렬 및 삽입 정렬은 O(n²)의 복잡도를 가집니다: 학습용으로는 적합하지만 대량 데이터에서는 느립니다.
fopen은 파일 포인터를 반환하며, 모드 문자열은 동작을 지정합니다 — "w"는 쓰기, "r"는 읽기, "a"는 추가(append). 쓰기는 fprintf로, 읽기는 fscanf로, 작업 완료 시 항상 fclose을 수행하십시오.
#include <stdio.h>
int main(void) {
FILE *out = fopen("scores.txt", "w"); // open for writing
if (out == NULL) {
perror("scores.txt");
return 1;
}
fprintf(out, "Alice 80\nBob 95\n");
fclose(out);
FILE *in = fopen("scores.txt", "r"); // open for reading
if (in == NULL) {
perror("scores.txt");
return 1;
}
char name[20];
int score;
while (fscanf(in, "%19s %d", name, &score) == 2) { // %19s leaves room for '\0'
printf("%s -> %d\n", name, score);
}
fclose(in);
return 0;
}
fopen → read/write → fclose
12.2
반환 코드를 통한 에러 처리
C에는 내장된 예외 처리가 없습니다. 함수는 반환 코드를 통해 결과를 보고할 수 있으며, 결과를 사용하기 전에 해당 함수의 규칙을 확인해야 합니다. 아래 예시는 성공에 0, 실패에 -1을 사용합니다. 대신 fopen은 스트림 포인터를 반환하거나 실패 시 NULL을 반환합니다.
#include <stdio.h>
// returns 0 on success, -1 if the divisor is 0
int safe_divide(int a, int b, int *result) {
if (b == 0) return -1; // error code
*result = a / b;
return 0; // success
}
int main(void) {
int r;
if (safe_divide(10, 2, &r) == 0)
printf("10 / 2 = %d\n", r); // 10 / 2 = 5
if (safe_divide(10, 0, &r) != 0)
printf("cannot divide by zero\n"); // error reported
return 0;
}
비트(bit)는 단일 0 또는 1이며, 숫자는 이진수로 저장됩니다. 비트 연산자는 비트 자체에 작동합니다: & AND, | OR, ^ XOR, << 좌변위(shift left, 각 단계 ×2), >> 우변위(shift right, ÷2).
#include <stdio.h>
int main(void) {
int a = 12; // 1100
int b = 10; // 1010
printf("%d\n", a & b); // 8 AND -> 1000
printf("%d\n", a | b); // 14 OR -> 1110
printf("%d\n", a ^ b); // 6 XOR -> 0110
printf("%d\n", a << 1); // 24 left shift
printf("%d\n", a >> 1); // 6 right shift
return 0;
}
Hexadecimal (base 16) writes binary compactly: one hex digit is exactly four bits. Write hex literals with 0x; print with %x:
#include <stdio.h>
int main(void) {
printf("%d\n", 0xFF); // 255 (0x marks a hex literal)
printf("%x\n", 255); // ff
printf("%x\n", 12); // c
return 0;
}
비트 연산자는 정수의 비트에 작용합니다
13.2
루스 인코딩(RLE)
Run-length encoding(RLE)은 간단한 압축 방법입니다: 연속된 동일한 문자의 묶음을 개수와 해당 문자로 교체합니다. 무손실(lossless) 방식이라 원본을 완전히 복원할 수 있습니다.
#include <stdio.h>
#include <string.h>
int main(void) {
char *s = "aaabbc";
int n = strlen(s);
for (int i = 0; i < n; ) {
char c = s[i];
int run = 0;
while (i < n && s[i] == c) { run++; i++; }
printf("%d%c", run, c); // 3a2b1c
}
printf("\n");
return 0;
}
Common mistakes
&는 비트 AND이며, &&는 논리 AND입니다. 혼동하지 마십시오.
좌변위 << 1은 값을 두 배로, 우변위 >> 1은 반으로 만듭니다.
비트 n의 값은 1 << n입니다(C에는 ** 지수 연산자가 없음); 비트를 확인하려면 (x >> n) & 1을 사용하십시오.
전预处理(preprocessor)는 컴파일 전에 실행됩니다. #define은 매크로를 생성하여 전역에서 plain text를 교체합니다. const은 변경할 수 없는 상수를 만듭니다. 함수 내부의 static는 호출 간 변수 값을 유지합니다. enum(열거형)은 0부터 시작하는 일련의 정수에 이름을 부여합니다.
#include <stdio.h>
#define MAX 100 // macro: text replaced before compiling
enum Color { RED, GREEN, BLUE }; // named integers 0, 1, 2
int next_id(void) {
static int count = 0; // keeps its value between calls
count++;
return count;
}
int main(void) {
const double PI = 3.14; // cannot be changed
printf("%d %.2f\n", MAX, PI); // 100 3.14
printf("%d %d %d\n", RED, GREEN, BLUE); // 0 1 2
int a = next_id();
int b = next_id();
printf("%d %d\n", a, b); // 1 2
return 0;
}
Bigger programs split across files: declarations go in a header file (mine.h), included with #include "mine.h" — quotes mean your own file, < > means the standard library. An include guard (#ifndef MINE_H / #define MINE_H / #endif) stops a header being included twice.
Common mistakes
#define은 타입 체크 없이 plain text 교체를 수행하므로, 매크로 본체와 인자를 괄호로 감싸십시오.