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?
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";