7.4 Pointers and Strings
C++ usually uses std::string for text. This section studies C-style null-terminated character strings because they reveal how arrays and pointers interact.
Character array vs. character pointer
A string defined as a character array stores each character in the array, and you can modify it just like an ordinary array.
char s1[] = "hello";
s1[0] = 'H'; // modifiable
std::cout << s1 << std::endl; // HelloIf a pointer points to a string literal, that string usually lives in a read-only constant area. In C++, string literals should be treated as const char*; modifying them is not allowed.
const char* s2 = "hello";
// s2[0] = 'H'; // wrong: do not modify a string literal
std::cout << s2 << std::endl;Use a character array when you need to modify the characters, and const char* for a literal that stays read-only.
Assigning a pointer does not copy the string
Assigning one string pointer to another does not create a new string; it just makes both pointers refer to the same memory. A change made through one is visible through the other.
char str[] = "hello";
char *s = str;
char *t = s; // s and t point to the same string
s[0] = 'H';
std::cout << s << std::endl; // Hello
std::cout << t << std::endl; // HelloWalking a string with a pointer
A C-style string ends with '\0'. When walking it with a pointer, *s is the current character and s++ moves forward one step, stopping at '\0'.
const char* s = "hello";
while (*s != '\0') {
std::cout << *s;
s++;
}