Is it necessary to supply the null character when declaring an character's array?

前端 未结 3 1231
孤城傲影
孤城傲影 2020-12-21 09:22

A string constant in C is stored as a character array, while creating such an array element by element, is it necessary to supply the null character.

I need to store

相关标签:
3条回答
  • 2020-12-21 09:38

    While storing the phrase in an array, do I need to account for the null character and allocate an additional space or do I just need t mention the number of characters that I need to store?

    Yes, you should count null chars to allocate additional space. You must note Important point here:

    S[number]= "hello\n";
    

    Will append \0 in S[] array if number value is equals to (or grater than) length of string "hello\n" pule one for \0 char (or if you don't give size at all as s[] = "hello\n";).

    From: ISO/IEC 9899:201x Committee Draft April 12, 2011 N1570:

    6.7.9 [Initialization]

    [...]
    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.
    [..]
    EXAMPLE 8 The declaration

    char s[] = "abc", t[3] = "abc";
    

    defines ``plain'' char array objects s and t whose elements are initialized with character string literals. This declaration is identical to:

      char s[] = { 'a', 'b', 'c', '\0' },
           t[] = { 'a', 'b', 'c' }; // you are missing this point
    

    The contents of the arrays are modifiable. On the other hand, the declaration

     char *p = "abc";
    

    defines p with type pointer to char'' and initializes it to point to an object with typearray of char'' with length 4 whose elements are initialized with a character string literal. If an attempt is made to use p to modify the contents of the array, the behavior is undefined.

    So as I commented to your question: it depends on value of number you give in declaration in declaration. it may add '\0' char (in most cases) or may not add (in one valid declaration). This is very important point that most answers are missing.

    More preciously:

    Note "hello" is six char long string (including string termination nul char '\0' )

    S[6]= "hello";
    

    is same as:

    S[6]= {'h', 'e', 'l', 'l', 'o', '\0'};
    // ^ is 6
    

    But

    S[5]= "hello";
    

    is valid in C, But don't append nul \0 char. It is equivalent to:

    S[5]= {'h', 'e', 'l', 'l', 'o'};
    // ^  is 5 
    

    Now this is very important to note, In this declaration, if size is given five = 5 in declaration then you can use loop to print chars as for(i = 0; i < sizeof(S); i++), but you can't use %s or functions like strcpy on S[] — using this call undefined behavior.

    Beside this, I would also suggest you always use -Wall and -pedantic flag when you compiles your code. Now see how this works:

    Lets compile this code, with char s[4] = "hello"; :

    int main(){
      char s[4] = "hello";
      int i = 0;
      for (i = 0; i < sizeof s; i++) 
       printf("%c", s[i]);
      printf("\n");
      return 0;
    }
    

    You will get a warning as follows:

    $ gcc -Wall -pedantic x.c
    x.c: In function ‘main’:
    x.c:3:15: warning: initializer-string for array of chars is too long 
    [enabled by default]
    

    But code is valid in C with char s[5] = "hello"; compile same code it will not give any warning to you that also implies it is a valid code but obviously it don't add \0.

    #include <stdio.h>
    int main(){
      char s[5] = "hello";
      int i = 0;
      for (i = 0; i < sizeof s; i++) 
       printf("%c", s[i]);
      printf("\n");
      return 0;
    }
    

    Check this (you should notice this time compiler don't emits any warning):

    $ gcc -Wall -pedantic x.c
    @:~$ ./a.out 
    hello
    

    But this time we should use printf("%s", s); it will call undefined behavior.

    So when you create an array with string literal then better is to avoid size in declaration, as:

      char s[] = "hello";
    

    But this is just same as char s[6] = "hello"; And you can't append a new char(s) to s[] as strcat(s, " world!").

    If you intended to modify s[] latter in your code then you may like to create a string of sufficiently large size as:

     char s[100] = "hello";
    

    Now strcat(s, " world!") is perfectly valid code.

    0 讨论(0)
  • 2020-12-21 09:49

    If you are going to use C-string functions, like strlen, - then answer is YES. Your string should be null-terminated. If you introduce your custom functions to deal with string - you can store it however you like.

    It's important to mention, that if you create an array using string constant, it reserves space for null-character automatically. E.g. output for the following code:

    char s[] = "hello";
    printf("%d", sizeof(s) / sizeof(char));
    

    is

    6
    

    which is 5 for 'h, 'e', 'l', 'l', 'o' and 1 for '\0'.

    0 讨论(0)
  • 2020-12-21 09:51

    No, but you should leave out number

    char S[]= "hello\n";
    

    will have the trailing 0 character and the array sized as needed.

    With number too small you could accidentally cut off the 0 character.

    0 讨论(0)
提交回复
热议问题