What is the difference between:
char s  = "text"; char * ps = "text1"; STD :: STRING STR = "TEXT3";
and what better to use?
Answer 1, Authority 100%
char s  = "text";
An array ad
char  and initializing this array string literal
"text" . That is
s is just an array of five characters:
\ 0 .
You can change it:
s  = 'n'; / * S: "Next" * /
But you cannot cross the array itself
S (this is an array):
char s  = "text"; / * OK * / S = "ANOTHER TEXT"; /* This is mistake. * /
char * s = "text"; / * to C++ 11 * / Const char * s = "text"; / * Starting C++ 11 * /
Announcement of the
char * and assigning a pointer to the first element of the string literal
"Text" . Attempt to change this string literal (
s  = 'A' , for example), it is uncertain behavior.
However, the pointer itself can be overwritten:
const char * p = "text"; / * OK * / P = "ANOTHER TEXT"; / * OK * /
Starting with C++ 11 String literals can be directly assigned only
const char * (i.e. only signs on Constant
std :: string s = "text";
Creating an object
std :: String and assigning it
const char * 1 sup>. That is,
s is not an array and not a pointer, but an object.
Line class in turn contains many different features: copy, comparison, concatenation, change, search for substring and so on. What rows in the style of C (arrays) are certainly deprived (if not taken into account
& lt; CString & GT; ).
What is better to use?
Use needs something more suitable for a specific task. Each reprimanded “string” has its own applications.
- implicit types of type: Assigns not
Const char [n], which is the types for all string literals, namely the pointer. See also see Assignment Operator Line Class.
First – an array of fixed size symbols, apparently, in the stack (if you did not declare it as global).
Second – the pointer to the string, zausenny somewhere in the memory (where the compiler will put). It is impossible to change it, you can only specify another line.
Line class that supports weight of functions, and stores a string somewhere (most likely, in dynamic memory, but it can be short and in its internal buffer).
and then depends on what you want to use it.
- Guided by CPP Core Guidlines , I can say:
It should be used for meaningful text strings, i.e. where
Symbols in the amount are words, suggestions, expressions and
charare used when you need to present
Separately standing symbols, the concatenation of which does not make sense (we are talking about how costs strong>do, this does not say that it is done everywhere).
- About the difference between
char Introductory read here . If briefly:
char *pointer to the constant string, and
char – a variable array of characters.