본문 바로가기
C언어/배열

[C언어] 배열에 문자를 하나씩 입력하는 경우 (널문자의 중요성)

by bigpicture 2022. 7. 15.
반응형

배열을 하나 정의하고 문자를 하나씩 입력해봅시다. 

#include <stdio.h>

int main()
{
    char str[10];
    
    str[0]='A';
    str[1]='B';
    
    printf("%s",str);

    return 0;
}

 

 

쓰레기 값이 출력됩니다. 널 문자를 이용하여 AB만 출력되도록 해봅시다. 문자열은 널 문자 까지만 출력됩니다. 널 문자는 \0 입니다. 

 

#include <stdio.h>

int main()
{
    char str[10];
    
    str[0]='A';
    str[1]='B';
    str[2]='\0';
    
    printf("%s",str);

    return 0;
}

 

반응형

댓글