Search code examples
carrayscharinitializationbuffer

C char array initialization: what happens if there are less characters in the string literal than the array size?


I'm not sure what will be in the char array after initialization in the following ways.

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

For case 2, I think buf[0] should be ' ', buf[1] should be '\0', and from buf[2] to buf[9] will be random content. For case 3, I think buf[0] should be 'a', buf[1] should be '\0', and from buf[2] to buf[9] will be random content.

Is that correct?

And for the case 1, what will be in the buf? buf[0] == '\0' and from buf[1] to buf[9] will be random content?


Solution

    1. The first declaration:

       char buf[10] = "";
      

      is equivalent to

       char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
      
    2. The second declaration:

       char buf[10] = " ";
      

      is equivalent to

       char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};
      
    3. The third declaration:

       char buf[10] = "a";
      

      is equivalent to

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

    As you can see, no random content: if there are fewer initializers, the remaining of the array is initialized with 0. This the case even if the array is declared inside a function.