본문 바로가기

C Language

올바른 포인터 접근 출력법 | Correct Approach for Double/Single Pointer


int main() {
char ch[] = "Hello World Hi";

char **my;

*my = ch;

printf("%s\n",*my);
return 0;
} 라는 코드는 왜 제대로 작동되지 않을까요? 그것은 바로 포인터를 제대로 할당하지 않았기 때문입니다.

 

이 코드에서 "Hello World Hi"가 출력되지 않는 이유는 다음과 같습니다:
메모리 할당 문제:
char **my;는 포인터에 대한 포인터를 선언하지만, 실제 메모리를 할당하지 않았습니다.
*my = ch;는 할당되지 않은 메모리에 값을 쓰려고 시도하므로 정의되지 않은 동작(undefined behavior)을 유발합니다.
포인터 타입 불일치:
ch는 char[] 타입이지만, my는 char** 타입입니다.
이러한 타입 불일치는 추가적인 문제를 야기할 수 있습니다.
잠재적 세그멘테이션 폴트:
할당되지 않은 메모리에 접근하려고 시도하므로, 프로그램이 세그멘테이션 폴트로 종료될 가능성이 높습니다.

 

올바른 접근1 ❘ Correct Approach
올바른 2중포인터 접근 ❘ Correct Approach for Double Pointer

This code doesn't output "Hello World Hi" for the following reasons:
Memory Allocation Issue:
char **my; declares a pointer to a pointer, but no actual memory is allocated.
*my = ch; attempts to write to unallocated memory, causing undefined behavior.
Pointer Type Mismatch:
ch is of type char[], while my is of type char**.
This type mismatch can lead to additional problems.
Potential Segmentation Fault:
Attempting to access unallocated memory is likely to result in a segmentation fault, terminating the program.