Why does gcc allow char array initialization with string literal larger than array?

前端 未结 4 2036
攒了一身酷
攒了一身酷 2020-12-03 21:15
int main()
{
    char a[7] = \"Network\";
    return 0;
}

A string literal in C is terminated internally with a nul charac

4条回答
  •  無奈伤痛
    2020-12-03 21:46

    The preffered way of declaring a string literal is usually:

       char a[] = "Network";
       printf("size of a: %d\n", sizeof a); // The compiler 'knows' the size of a.
       // this prints '8'
    

    Let the compiler figure it out. It's cumbersome to manually specify the array size and keep it in sync with the string literal's actual length...

    So I guess GCC doesn't really bother with anything more than a warning.

提交回复
热议问题