What’s the difference between:
char s = "text"; char* ps = "text1"; std::string str = "text3";
And which is better to use?
Answer 1, authority 100%
char s = "text";
Declaring an array
char and initializing this array with the string literal
"text". That is,
sis just an array of five characters:
You can change it:
s = 'n'; /* s: "next" */
But you cannot reassign the
sarray itself (this is an array):
char s = "text"; /* OK */ s = "another text"; /* This is mistake. */
char *s = "text"; /* toC++11 */ const char *s = "text"; /* starting outC++11 */
Declaring a pointer
char *and assigning it a pointer to the first element of the
"text"string literal. Attempting to modify this string literal (
s = 'a'for example) is undefined behavior.
However, the pointer itself can be reassigned:
const char *p = "text"; /* OK */ p = "another text"; /* OK */
Since C++ 11, string literals can only be directly assigned to
const char *(i.e., only pointers to const char
std::string s = "text";
Create an object
std::stringand assign it
const char *1 . That is,
sis not an array or a pointer, but an object.
The string class, in turn, contains many different possibilities: copying, comparing, concatenating, modifying, searching for substrings, and so on. Of course, C-style strings (arrays) are devoid of that (apart from
Which is better to use?
You need to use what is more suitable for a specific task. Each of the “lines” discussed above has its own areas of application.
- An implicit casting is performed: it is not assigned to
const char [N], which is the type for all string literals, namely a pointer. Also see string class assignment operator
The first is a fixed size array of characters, apparently on the stack (unless you declare it global).
The second is a pointer to a string located somewhere in memory (where the compiler will put it). You cannot change it, you can only point to a different line.
A string class that supports a lot of functions, and stores the string somewhere (most likely in heap, but can also store short strings in its internal buffer).
And then it depends on what you want to use it for.
- Guided by Cpp core guidlines I can say:
should be used for meaningful text strings, i.e. where
the symbols in the sum represent words, sentences, expressions and
chararrays are used when it is necessary to represent
stand-alone characters, the concatenation of which does not make sense (we are talking about how to to do, this does not mean that this is done everywhere).
- As for the difference between
char , I highly recommend reading here . In short:
char *is a pointer to a constant string, and
char is a mutable array of characters.