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%
1.
char s[] = "text";
Declaring an array s
of type char []
and initializing this array with the string literal "text"
. That is, s
is just an array of five characters: t
, e
, x
, t
, \0
.
You can change it:
s[0] = 'n'; /* s: "next" */
But you cannot reassign the s
array itself (this is an array):
char s[] = "text"; /* OK */
s = "another text"; /* This is mistake. */
2.
char *s = "text"; /* toC++11 */
const char *s = "text"; /* starting outC++11 */
Declaring a pointer s
of type char *
and assigning it a pointer to the first element of the "text"
string literal. Attempting to modify this string literal (s[0] = '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 char
).
3.
std::string s = "text";
Create an object s
of class std::string
and assign it const char *
1 . That is, s
is 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 <cstring>
).
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
Answer 2
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.
Answer 3
- Guided by Cpp core guidlines I can say:
std:string
should be used for meaningful text strings, i.e. where
the symbols in the sum represent words, sentences, expressions and
etc.char
arrays 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 *
andchar []
, I highly recommend reading here . In short:char *
is a pointer to a constant string, andchar []
is a mutable array of characters.