c++arraysinitializationdeclarationstring-literals

Initialisation of char array to string value, are the uninitialised indices set to null?


If I have the following:

char test[10] = "#";

Is test[1] through test[9] guaranteed to be \0? Or is only test[1] guaranteed to be \0?


Solution

  • This definition

    char test[10] = "#";
    

    is equivalent to

    char test[10] = { '#', '\0' };
    

    That is two elements of the array are initialized explicitly by the initializers. All other elements of the array will be zero initialized that is implicitly they will be set to '\0'

    According to the C++ Standard (section 8.5.2 Character arrays)

    3 If there are fewer initializers than there are array elements, each element not explicitly initialized shall be zero-initialized (8.5).