Two string literals have the same pointer value?

后端 未结 5 1636
慢半拍i
慢半拍i 2020-11-27 08:14

When I run this program using MinGW, im getting output as \"=\"

#include

using namespace std;

int main()
{
 char *str1 = \"Hello\";
 char *         


        
5条回答
  •  攒了一身酷
    2020-11-27 08:55

    The type of a string literal like "Hello" is array of const char, therefore, you are directing two pointers to something that is not allowed to ever change.

    The C++ standard gives compilers the freedom to merge identical constant values together (note that compilers are not required to do so).

    Related: The declarations are therefore invalid and must be modified to:

    const char *str1 = "Hello";
    const char *str2 = "Hello";
    

    or if you want

    char const *str1 = "Hello";
    char const *str2 = "Hello";
    

    which reads nicely when reading right-to-left:

    str1 is a pointer to const char
    

    .

提交回复
热议问题