C Language | Pointers | String Pointers
This article explains character arrays and pointers to strings. Do not modify a string literal through a pointer. To edit a string based on a literal, copy it into an array.
Pointers to String Literals
Initializing an array with a string literal stores the string in the array. What happens when a string literal appears in an expression other than an initializer? A string literal evaluates to a pointer to the string.
For example, printf("Kitty on your lap") passes a value of type char * to printf(). Where is that string stored?
Constants such as string literals and numbers are converted into binary data at compile time and stored in the executable file. When the program runs, the data is loaded into memory as constant values. The specific storage and loading behavior depends on the compiler and system.
Because a string literal is already stored in memory while a program runs, copying it into another array is useful only when character-level editing is needed. Choose between a pointer to the literal and a copied array according to your purpose.
char chStr[] = "Kitty on your lap";
This statement copies the literal into a new array named chStr. It is appropriate when you need to edit the resulting array. If you only need a variable that points to the string, copying is unnecessary.
char *chpStr = "Kitty on your lap";
This differs significantly from array initialization. chStr[] = "..." allocates an array large enough to store the string and copies the literal into it. In contrast, *chpStr = "Kitty on your lap" assigns the address of a string literal loaded from the executable.
Code 1
#include <stdio.h>
int main() {
char *chpStr = "Kitty on your lap";
printf("%s\n" , chpStr);
return 0;
}
Code 1 assigns the address of the literal "Kitty on your lap" to chpStr and displays the string. Do not modify a string literal through this pointer. Attempting to do so results in undefined behavior.