The Difference Between char str* And char str[]
Updated:
Let’s see the difference between this line of code:
char str_1[] = "hello world";
And this one:
char *str_2 = "hello world";
String literals and arrays
When we define str_1, the compiler creates a character array large enough to hold the string "hello world", which is an immutable string literal. Since we initialize str_1 with the content of this string literal, the compiler generates instructions to copy its contents into the str_1 array. And since str_1 is an array, we can access both reading and writing to all its elements.
str_1[0] = 'B'; /* We can do it, of course */
The main difference is that str_2 is simply a pointer initialized to the address of the string literal "hello world". This string literal will be placed in a particular, read-only memory region by the linker. So the most important consequence is that str_2 now points to an immutable string, and then performing a write operation like the following leads to the program crash.
str_2[0] = 'B'; /* Program crash! */
Instead, we can reassign the pointer value and make it point to the character array str_1, for example.
str_2 = str_1;
/* Or (same effect): */
str_2 = &str_1[0];
Now we can also modify str_1 content by using the str_2 pointer, as you can see in the following example.
char str_1[] = "hello world";
char *str_2 = "hello world";
str_2 = str_1;
str_2[0] = 'B'; /* Now we can do it */
printf("str_1: %s\n", str_1);
printf("str_2: %s\n", str_2);
With this code we get this output:
str_1: Bello world
str_2: Bello world