Behaviour of sizeof with string

前端 未结 2 1400
囚心锁ツ
囚心锁ツ 2021-01-20 03:36
‪#‎include‬ 
#include 
int main()
{
    printf(\"%d\\n\",sizeof(\"S\\065AB\"));
    printf(\"%d\\n\",sizeof(\"S65AB\"));
    printf(\"         


        
相关标签:
2条回答
  • 2021-01-20 03:46

    A literal character string is an array of exactly the size needed to hold all the characters and an extra terminating zero-byte.

    So, "hello" has type char[6] and sizeof yields 6.

    0 讨论(0)
  • 2021-01-20 03:55

    The size of a string literal is the number of characters in it including the trailing null byte that is added. If there embedded nulls in the string, they are immaterial; they get counted. It is unrelated to strlen() except that if the literal includes no embedded nulls, strlen(s) == sizeof(s) - 1.

    printf("%zu\n", sizeof("S\065AB"));      // 5: '\065' is a single character
    printf("%zu\n", sizeof("S65AB"));        // 6
    printf("%zu\n", sizeof("S\065\0AB"));    // 6: '\065' is a single character
    printf("%zu\n", sizeof("S\06\05\0AB"));  // 7: '\06' and '\05' are single chars
    printf("%zu\n", sizeof("S6\05AB"));      // 6: '\05' is a single character
    printf("%zu\n", sizeof("\0S65AB"));      // 7
    

    Note that '\377' is a valid octal constant, equivalent to '\xFF' or 255. You can use them in strings, too. The value '\0' is only a special case of a more general octal constant.

    Note that sizeof() evaluates to a value of type size_t, and the correct formatting type qualifier in C99 and C11 for size_t is z, and since it is unsigned, u is more appropriate than d, hence the "%zu\n" format that I used.

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