7.4 Pointers and Strings
Both arrays and pointers can represent a string, but they allocate memory differently, so they are used differently.
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
printf("%s\n", s1); // HelloIf a pointer points to a string literal, that string usually lives in a read-only constant area. Modifying the string through such a pointer is undefined behavior and often crashes the program.
char *s2 = "hello";
// s2[0] = 'H'; // wrong: do not modify a string literal
printf("%s\n", s2);Use a character array when you need to modify the string, and char * to a literal only when it 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';
printf("%s\n", s); // Hello
printf("%s\n", t); // HelloWalking a string with a pointer
A C string ends with '\0'. When walking it with a pointer, *s is the current character and s++ moves forward one step, stopping at '\0' — exactly how functions like strlen and strcpy work internally.
char *s = "hello";
while (*s != '\0') {
putchar(*s);
s++;
}