포인터는 메모리의 주소를 저장하는 변수이다. 포인터를 함수에 전달할 때 포인터의 위치와 주소값 변경에 대한 이해는 C 프로그래밍에서 중요하다. 포인터의 주소값이 함수 내에서 어떻게 영향을 받는지를 알아보자
포인터를 함수에 전달하면, 함수 내에서 포인터의 위치를 이동할 수 있다. 이 경우 포인터가 가리키는 데이터의 위치가 변경된다. 그러나 포인터 변수 자체의 주소값은 변경되지 않는다.
#include <stdio.h>
void move_pointer(char *ptr) {
ptr++; // 포인터의 위치를 이동
printf("Inside function, pointer points to: %c\n", *ptr); // 이동한 위치의 데이터 출력
}
int main() {
char str[] = "hello";
char *p = str; // 포인터 p는 str의 시작 주소를 가리킴
printf("Before function, pointer points to: %c\n", *p); // 원래 포인터가 가리키는 데이터 출력
move_pointer(p); // 포인터 p를 함수에 전달
printf("After function, pointer points to: %c\n", *p); // 포인터 주소는 변화 없음, 여전히 원래 데이터 출력
return 0;
}
출력 결과:
Before function, pointer points to: h
Inside function, pointer points to: e
After function, pointer points to: h
move_pointer 함수 내에서 포인터 ptr의 위치를 이동시키지만, 포인터 변수 p의 값은 변화가 없다.main 함수에서 포인터 p는 여전히 문자열 "hello"의 시작 주소를 가리키며, 포인터의 값(주소)은 그대로 유지된다.포인터 변수의 주소값을 함수 내에서 변경할 수 있다. 이를 위해 포인터의 포인터를 사용한다. 포인터의 포인터를 전달하면, 포인터 변수 자체가 가리키는 주소를 변경할 수 있다.
#include <stdio.h>
void change_pointer_value(char **ptr) {
static char new_str[] = "world"; // 새 문자열
*ptr = new_str; // 포인터가 새 문자열의 주소를 가리키도록 변경
}
int main() {
char str[] = "hello";
char *p = str; // 포인터 p는 str의 시작 주소를 가리킴
printf("Before function, pointer points to: %s\n", p); // 원래 문자열 출력
change_pointer_value(&p); // 포인터의 포인터를 함수에 전달
printf("After function, pointer points to: %s\n", p); // 새 문자열 출력
return 0;
}
출력 결과:
Before function, pointer points to: hello
After function, pointer points to: world
change_pointer_value 함수에서 포인터의 포인터를 사용하여 포인터 p가 가리키는 주소를 변경한다.main 함수에서 포인터 p는 new_str의 주소를 가리키게 되어, 문자열이 "world"로 변경된다.포인터의 위치와 주소값 변경을 이해하면 메모리 관리와 데이터 접근을 보다 효과적으로 수행할 수 있다.
https://github.com/eliarisalvares/libft_42sp/blob/master/ft_split.c
https://velog.io/@jen133/ftsplit
https://github.com/LazyVim/LazyVim