These two do not have the same behavior. s1 is a simple pointer that is initialized to point to some (usually read-only) memory area. s2 , on the other hand, defines a local array of size 5 and populates it with a copy of this string.
Formally, you are not allowed to change s1 , that is, to do something like s1[0] = 'a' . In particular, under strange circumstances, this can lead to the fact that all other "test" in your program will become "aest" , because they all have the same memory. This is why modern compilers scream when you write
char* s = "test";
On the other hand, s2 modification is allowed, as this is a local copy.
In other words, in the following example
const char* s1 = "test"; const char* s2 = "test"; char s3[] = "test"; char s4[] = "test";
s1 and s2 can very accurately indicate the same address in memory, and s3 and s4 - two different copies of the same line and are in different areas of memory.
If you write C ++, use std::string if you don't need an array of characters. If you need a modifiable array of characters, use char s[] . If you only need an immutable string, use const char* .
user1071136
source share