Difference between char* and char[]

前端 未结 7 1191
清歌不尽
清歌不尽 2020-11-27 03:32

I know this is a very basic question. I am confused as to why and how are the following different.

char str[] = \"Test\";
char *str = \"Test\";
相关标签:
7条回答
  • 2020-11-27 04:02

    Starting from C++11, the second expression is now invalid and must be written:

    const char *str = "Test";
    

    The relevant section of the standard is Appendix C section 1.1:

    Change: String literals made const

    The type of a string literal is changed from “array of char” to “array of const char.” The type of a char16_t string literal is changed from “array of some-integer-type” to “array of const char16_t.” The type of a char32_t string literal is changed from “array of some-integer-type” to “array of const char32_t.” The type of a wide string literal is changed from “array of wchar_t” to “array of const wchar_t.”

    Rationale: This avoids calling an inappropriate overloaded function, which might expect to be able to modify its argument.

    Effect on original feature: Change to semantics of well-defined feature.

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