String initialization with and without explicit trailing terminator

前端 未结 4 1336
梦谈多话
梦谈多话 2020-12-31 05:29

What is the difference between

char str1[32] = \"\\0\";

and

char str2[32] = \"\";
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-31 05:41

    Well, assuming the two cases are as follows (to avoid compiler errors):

    char str1[32] = "\0";
    char str2[32] = "";
    

    As people have stated, str1 is initialized with two null characters:

    char str1[32] = {'\0','\0'};
    char str2[32] = {'\0'};
    

    However, according to both the C and C++ standard, if part of an array is initialized, then remaining elements of the array are default initialized. For a character array, the remaining characters are all zero initialized (i.e. null characters), so the arrays are really initialized as:

    char str1[32] = {'\0','\0','\0','\0','\0','\0','\0','\0',
                     '\0','\0','\0','\0','\0','\0','\0','\0',
                     '\0','\0','\0','\0','\0','\0','\0','\0',
                     '\0','\0','\0','\0','\0','\0','\0','\0'};
    char str2[32] = {'\0','\0','\0','\0','\0','\0','\0','\0',
                     '\0','\0','\0','\0','\0','\0','\0','\0',
                     '\0','\0','\0','\0','\0','\0','\0','\0',
                     '\0','\0','\0','\0','\0','\0','\0','\0'};
    

    So, in the end, there really is no difference between the two.

提交回复
热议问题