0

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?

B.Castarunza
  • 135
  • 12
  • Have you tried it? – Marco Bonelli Jun 26 '20 at 15:43
  • Does this answer your question? [standard conversions: Array-to-pointer conversion](https://stackoverflow.com/questions/4223617/standard-conversions-array-to-pointer-conversion) – UkFLSUI Jun 26 '20 at 15:47
  • Are you asking how to make the pointer point to the string? If so, which of the two strings are you talking about? (The string constant, "hello", or the character array `str` that contains the string "hello"?) Given that you didn't make `ptr` a pointer to `const char *`, I would assume the array. Is that correct? – David Schwartz Jun 26 '20 at 15:51
  • 1
    You *cannot* assign a string to a pointer. A string is a null-terminated array of characters. You *can* assign the address of the first character to a pointer. If you write `ptr = str`, then `ptr` will point to the first char of `str` (the 'h' that has been copied and assigned at runtime, not the `h` that is in the string constant). – William Pursell Jun 26 '20 at 15:56

1 Answers1

4

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