programing

c에서 printf를 통해 char array를 인쇄하는 방법?

starjava 2023. 10. 9. 21:17
반응형

c에서 printf를 통해 char array를 인쇄하는 방법?

이로 인해 분할 오류가 발생합니다.수정해야 할 사항은 무엇입니까?

int main(void)
{
    char a_static = {'q', 'w', 'e', 'r'};
    char b_static = {'a', 's', 'd', 'f'};

    printf("\n value of a_static: %s", a_static);
    printf("\n value of b_static: %s\n", b_static);
}

게시된 코드가 올바르지 않습니다.a_static그리고.b_static배열로 정의해야 합니다.

코드를 수정하는 두 가지 방법이 있습니다.

  • null 터미네이터를 추가하여 이러한 배열을 적절한 C 문자열로 만들 수 있습니다.

    #include <stdio.h>
    
    int main(void) {
        char a_static[] = { 'q', 'w', 'e', 'r', '\0' };
        char b_static[] = { 'a', 's', 'd', 'f', '\0' };
    
        printf("value of a_static: %s\n", a_static);
        printf("value of b_static: %s\n", b_static);
        return 0;
    }
    
  • 다른 방법으로.printf는 정밀도 필드를 사용하여 null로 종료되지 않은 배열의 내용을 인쇄할 수 있습니다.

    #include <stdio.h>
    
    int main(void) {
        char a_static[] = { 'q', 'w', 'e', 'r' };
        char b_static[] = { 'a', 's', 'd', 'f' };
    
        printf("value of a_static: %.4s\n", a_static);
        printf("value of b_static: %.*s\n", (int)sizeof(b_static), b_static);
        return 0;
    }
    

    다음에 주어진 정밀도..문자열에서 출력할 최대 문자 수를 지정합니다.그것은 10진수로 주어질 수도 있고 다음과 같이 주어질 수도 있습니다.*그리고 제공되는int의 앞에서 논쟁하기char포인팅합니다.

로 인해 아래 문장 때문에 세그먼트화 오류가 발생합니다.

char a_static = {'q', 'w', 'e', 'r'};

a_static그래야 한다char array여러 개의 캐릭터를 가지고 있는 것처럼.

 char a_static[] = {'q', 'w', 'e', 'r','\0'}; /* add null terminator at end of array */

마찬가지로b_static

char b_static[] = {'a', 's', 'd', 'f','\0'};

선언 대신 배열을 사용해야 합니다.

a_static
b_static

변수로서

그럼 이렇게 생겼군요.

int main()
{
  char a_static[] = {'q', 'w', 'e', 'r','\0'};
  char b_static[] = {'a', 's', 'd', 'f','\0'};
  printf("a_static=%s,b_static=%s",a_static,b_static);
  return 0;
}

C Style Strings를 사용하고 있는데 C Style String은 0으로 종료됩니다.예를 들어, 문자 배열을 사용하여 "alien"을 인쇄하려면 다음과 같이 하십시오.

char mystring[6] = { 'a' , 'l', 'i', 'e' , 'n', 0}; //see the last zero? That is what you are missing (that's why C Style String are also named null terminated strings, because they need that zero)
printf("mystring is \"%s\"",mystring);

출력은 다음과 같아야 합니다.

나의 문자열은 "alien" 입니다.

코드로 돌아가서 보면 다음과 같습니다.

int main(void) 
{
  char a_static[5] = {'q', 'w', 'e', 'r', 0};
  char b_static[5] = {'a', 's', 'd', 'f', 0}; 
  printf("\n value of a_static: %s", a_static); 
  printf("\n value of b_static: %s\n", b_static); 
  return 0;//return 0 means the program executed correctly
}

그런데 배열 대신 포인터(스트링을 수정할 필요가 없는 경우)를 사용할 수 있습니다.

char *string = "my string"; //note: "my string" is a string literal

문자열 리터럴을 사용하여 문자 배열을 초기화할 수도 있습니다.

char mystring[6] = "alien"; //the zero is put by the compiler at the end 

또한: C Style Strings에서 작동하는 함수(예: printf, sscanf, strcmp, strcpy 등)는 문자열의 끝을 알기 위해 0이 필요합니다.

이 답변을 통해 무언가를 배웠기를 바랍니다.

언급URL : https://stackoverflow.com/questions/50312194/how-to-print-a-char-array-in-c-through-printf

반응형