1. 포인터를 이용한 배열 값 탐색
배열 내 최댓값과 최솟값을 찾는 과정에서 포인터를 활용하면 함수 호출 시 여러 값을 동시에 반환하는 효과를 낼 수 있습니다.
#include <stdio.h>
void calculate_range(int arr[], int size, int *min_ptr, int *max_ptr) {
*min_ptr = *max_ptr = arr[0];
for (int i = 1; i < size; ++i) {
if (arr[i] < *min_ptr) *min_ptr = arr[i];
if (arr[i] > *max_ptr) *max_ptr = arr[i];
}
}
int main() {
int data[] = {12, 5, 8, 20, 3};
int min_val, max_val;
calculate_range(data, 5, &min_val, &max_val);
printf("Min: %d, Max: %d\n", min_val, max_val);
return 0;
}
2. 문자열 조작과 메모리 관리
문자열을 다룰 때 배열(고정 메모리)과 포인터(주소 참조)의 차이를 이해하는 것이 중요합니다. 아래 코드는 포인터 변수를 사용하여 문자열의 내용을 바꾸지 않고 주소만 교환하는 방식입니다.
#include <stdio.h>
int main() {
char *s1 = "Hello";
char *s2 = "World";
char *temp;
// 포인터가 가리키는 주소 값 교환
temp = s1;
s1 = s2;
s2 = temp;
printf("s1: %s, s2: %s\n", s1, s2);
return 0;
}
3. 다차원 배열의 포인터 접근
2차원 배열은 메모리상에서 연속된 1차원 공간으로 존재합니다. int (*ptr)[4]와 같은 배열 포인터를 사용하면 2차원 구조를 유지하며 요소에 접근할 수 있습니다.
#include <stdio.h>
int main() {
int grid[2][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}};
int (*ptr)[4] = grid;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 4; ++j) {
printf("%d ", ptr[i][j]);
}
printf("\n");
}
return 0;
}
4. 문자열 검색 및 대체 함수
문자열 내의 특정 문자를 찾아 다른 문자로 치환하는 로직입니다. 포인터 연산을 통해 문자열 끝(null terminator)까지 효율적으로 순회합니다.
void modify_char(char *str, char target, char replacement) {
while (*str) {
if (*str == target) *str = replacement;
str++;
}
}
5. 간단한 암호화 알고리즘(Caesar Cipher)
사용자로부터 입력받은 문자열을 정해진 숫자만큼 밀어 암호화하고, 다시 복호화하는 기능입니다.
void encrypt(char *text, int shift) {
while (*text) {
if (*text >= 'a' && *text <= 'z')
*text = 'a' + (*text - 'a' + shift) % 26;
text++;
}
}
6. 커맨드라인 인자 정렬
argc와 argv를 활용하여 프로그램 실행 시 전달된 인자들을 알파벳 순으로 정렬하는 방식입니다. 포인터 배열을 교체하여 정렬을 수행합니다.
#include <string.h>
// 버블 정렬을 통한 argv 정렬 예시 생략