Pointer to const char vs char array vs std::string

前端 未结 7 2039
不思量自难忘°
不思量自难忘° 2020-12-16 20:48

Here I\'ve two lines of code

const char * s1 = \"test\";
char s2 [] = \"test\";

Both lines of code have the same behavior, so I cannot see

7条回答
  •  心在旅途
    2020-12-16 21:14

    const char * s1 = "test";
    char s2 [] = "test";
    

    These two aren't identical. s1 is immutable: it points to constant memory. Modifying string literals is undefined behaviour.

    And yes, in C++ you should prefer std::string.

提交回复
热议问题