Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 any difference whether I should prefer s1 over s2 or vice-versa. In addition to s1 and s2, there is also the way of using std::string. I think the way of using std::string is the most elegant. While looking at other code, I often see that people either use const char * or char s []. Thus, my question is now, when should I use const char * s1 or char s [] or std::string? What are the differences and in which situations should I use which approach?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
472 views
Welcome To Ask or Share your Answers For Others

1 Answer

POINTERS
--------

char const* s1 = "test";  // pointer to string literal - do not modify!

char* s1       = "test";  // pointer to string literal - do not modify!
                          //   (conversion to non-const deprecated in C++03 and
                          //       disallowed in C++11)

ARRAYS
------

char s1[5]     = "test";  // mutable character array copied from string literal
                          //    - do what you like with it!

char s1[]      = "test";  // as above, but with size deduced from initialisation



CLASS-TYPE OBJECTS
------------------

std::string s1 = "test";  // C++ string object with data copied from string
                          //    literal - almost always what you *really* want

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...