Programming

C 문자 배열 초기화

procodes 2020. 8. 27. 22:12
반응형

C 문자 배열 초기화


다음과 같은 방법으로 초기화 후 char 배열에 무엇이 있을지 잘 모르겠습니다.

1. char buf[10] = "";
2. char buf[10] = " ";
3.char buf[10] = "a";

경우 2, 나는 생각 buf[0]해야한다 ' ', buf[1]해야한다 '\0', 그리고에서 buf[2]buf[9]임의의 콘텐츠 될 것입니다. 케이스 3의 경우 , 이어야하고 , '\ 0' buf[0]이어야하며 'a', to 는 임의의 내용이 될 것입니다.buf[1]buf[2]buf[9]

그 맞습니까?

그리고 케이스 1의 경우 buf? buf[0] == '\0'과에서 buf[1]하는 것은 buf[9]임의의 콘텐츠 것인가?


이것은 배열을 초기화하는 방법이 아니라 다음을위한 것입니다.

  1. 첫 번째 선언 :

    char buf[10] = "";
    

    다음과 같다

    char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    
  2. 두 번째 선언 :

    char buf[10] = " ";
    

    다음과 같다

    char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};
    
  3. 세 번째 선언 :

    char buf[10] = "a";
    

    다음과 같다

    char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};
    

보시다시피 임의의 콘텐츠는 없습니다. 초기화 프로그램이 적 으면 나머지 배열은 0. 이것은 배열이 함수 내에서 선언 된 경우에도 마찬가지입니다.


편집 : OP (또는 편집자)는이 답변을 제공 한 후 원래 질문의 일부 작은 따옴표를 큰 따옴표로 자동 변경했습니다.

코드로 인해 컴파일러 오류가 발생합니다. 첫 번째 코드 조각 :

char buf[10] ; buf = ''

이중 불법입니다. 첫째, C에는 비어있는 char. 다음과 같이 큰 따옴표를 사용하여 빈 문자열을 지정할 수 있습니다.

char* buf = ""; 

그러면 NUL문자열에 대한 포인터가 제공됩니다 . 즉, 문자 만있는 단일 문자 문자열입니다 NUL. 그러나 그 안에 아무것도없는 작은 따옴표는 사용할 수 없습니다. 즉, 정의되지 않았습니다. NUL문자 를 지정해야하는 경우 지정해야합니다.

char buf = '\0';

백 슬래시는 문자와 구별하기 위해 필요합니다 '0'.

char buf = 0;

똑같은 일을 해내지만, 전자는 좀 덜 애매 모호하다고 생각합니다.

둘째, 배열을 정의한 후에는 초기화 할 수 없습니다.

char buf[10];

배열을 선언하고 정의합니다. 배열 식별자 buf는 이제 메모리의 주소이며 buf할당을 통해 포인트 위치를 변경할 수 없습니다 . 그래서

buf =     // anything on RHS

불법입니다. 두 번째 및 세 번째 코드 조각은 이러한 이유로 불법입니다.

배열을 초기화하려면 정의 할 때 수행해야합니다.

char buf [10] = ' ';

첫 번째 문자는 공백 '\040'이고 나머지는 NUL, 즉 '\0'. 이니셜 라이저를 사용하여 배열을 선언하고 정의하면 지정된 초기 값이있는 배열 요소 (있는 경우)를 지나서 배열 요소가 자동으로 0. "무작위 콘텐츠"는 없습니다.

다음과 같이 배열을 선언하고 정의하지만 초기화하지 않는 경우 :

char buf [10];

모든 요소에 무작위 콘텐츠가 있습니다.


  1. 이들은 동등합니다

    char buf[10] = "";
    char buf[10] = {0};
    char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    
  2. 이들은 동등합니다

    char buf[10] = " ";
    char buf[10] = {' '};
    char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};
    
  3. 이들은 동등합니다

    char buf[10] = "a";
    char buf[10] = {'a'};
    char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};
    

C11 표준 초안 n1570 6.7.9 초기화의 관련 부분은 다음과 같습니다.

14 An array of character type may be initialized by a character string literal or UTF-8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

and

21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Thus, the '\0' is appended, if there is enough space, and the remaining characters are initialized with the value that a static char c; would be initialized within a function.

Finally,

10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:

[--]

  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;

[--]

Thus, char being an arithmetic type the remainder of the array is also guaranteed to be initialized with zeroes.


Interestingly enough, it is possible to initialize arrays in any way at any time in the program, provided they are members of a struct or union.

Example program:

#include <stdio.h>

struct ccont
{
  char array[32];
};

struct icont
{
  int array[32];
};

int main()
{
  int  cnt;
  char carray[32] = { 'A', 66, 6*11+1 };    // 'A', 'B', 'C', '\0', '\0', ...
  int  iarray[32] = { 67, 42, 25 };

  struct ccont cc = { 0 };
  struct icont ic = { 0 };

  /*  these don't work
  carray = { [0]=1 };           // expected expression before '{' token
  carray = { [0 ... 31]=1 };    // (likewise)
  carray = (char[32]){ [0]=3 }; // incompatible types when assigning to type 'char[32]' from type 'char *'
  iarray = (int[32]){ 1 };      // (likewise, but s/char/int/g)
  */

  // but these perfectly work...
  cc = (struct ccont){ .array='a' };        // 'a', '\0', '\0', '\0', ...
  // the following is a gcc extension, 
  cc = (struct ccont){ .array={ [0 ... 2]='a' } };  // 'a', 'a', 'a', '\0', '\0', ...
  ic = (struct icont){ .array={ 42,67 } };      // 42, 67, 0, 0, 0, ...
  // index ranges can overlap, the latter override the former
  // (no compiler warning with -Wall -Wextra)
  ic = (struct icont){ .array={ [0 ... 1]=42, [1 ... 2]=67 } }; // 42, 67, 67, 0, 0, ...

  for (cnt=0; cnt<5; cnt++)
    printf("%2d %c %2d %c\n",iarray[cnt], carray[cnt],ic.array[cnt],cc.array[cnt]);

  return 0;
}

I'm not sure but I commonly initialize an array to "" in that case I don't need worry about the null end of the string.

main() {
    void something(char[]);
    char s[100] = "";

    something(s);
    printf("%s", s);
}

void something(char s[]) {
    // ... do something, pass the output to s
    // no need to add s[i] = '\0'; because all unused slot is already set to '\0'
}

참고URL : https://stackoverflow.com/questions/18688971/c-char-array-initialization

반응형