At very first, the string "hello"
actually is an array located somewhere in (immutable!) memory.
You can assign it to a pointer, which is what you do in second example (char* ptr = ...
). In this case, the pointer just points to that immutable array, i. e. holds the array's address. Recommendation at this point: Although legal in C (unlike C++), don't assign string literals to char*
pointers, assign them only to char const*
pointers; this reflects immutability much better.
In the second example, you use the first array (the literal) to initialise another array (str
). This other array str
(if not provided explicit length, as in the example) will use the first array's length and copy the contents of. This second array isn't immutable any more and you can modify it (as long as you do not exceed its bounds).
Assignment: Arrays decay to pointers automatically, if the context they are used in requires a pointer. This is why your first assignment example works, you assign a pointer (the one the array decayed to) to another one (ptr
). Actually, exactly the same as in your second initialisation example, you don't do anything different there either...
But arrays aren't pointers, and pointers never decay backwards to arrays. This is why the second assignment example doesn't work.