I just wanted to ask this:
In this piece of code I create a string and a pointer, what is the correct way to assign this string to the pointer?
char str[10] = "hello"; char* ptr Does it work with ptr = str? If not, why?
What is the correct way to assign this string to the pointer?
None. You cannot assign a string to a pointer. You only can assign the pointer by the address of the first element of the array str, which was initialized by the string "hello". It's a subtle but important difference.
Does it work with
ptr = str?
Yes, but it doesn't assign the string to the pointer. str decays to a pointer to the first element of the array of char str. After that, ptr is pointing to the array str which contains the string "hello".
If you don't want to modify the string, You could simplify the code by initializing the pointer to point to a string literal, which is stored in read-only memory instead of an modifiable array of char:
const char* ptr = "hello";
strthat contains the string "hello"?) Given that you didn't makeptra pointer toconst char *, I would assume the array. Is that correct?ptr = str, thenptrwill point to the first char ofstr(the 'h' that has been copied and assigned at runtime, not thehthat is in the string constant).