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** 타입입니다.
이러한 타입 불일치는 추가적인 문제를 야기할 수 있습니다.
잠재적 세그멘테이션 폴트:
할당되지 않은 메모리에 접근하려고 시도하므로, 프로그램이 세그멘테이션 폴트로 종료될 가능성이 높습니다.
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.
'C Language' 카테고리의 다른 글
Hello World Hi 에서 World Hi를 출력하도록 하는 법. (10) | 2025.01.01 |
---|---|
이중포인터 사용 이점 | The Advantages of using a double pointer (0) | 2025.01.01 |
malloc으로 할당해서 쓰는 이유 | The reason for allocating memory by using malloc (0) | 2025.01.01 |
linked list에서 s_list와 t_list로 구분하는 의미 | The reason of separating s_list from t_list in linked list. (2) | 2025.01.01 |
strncpy(out[k++], &str[j], i-j) (2) | 2024.12.14 |