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?

4
  • Have you tried it? Commented Jun 26, 2020 at 15:43
  • Does this answer your question? standard conversions: Array-to-pointer conversion Commented Jun 26, 2020 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? Commented Jun 26, 2020 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). Commented Jun 26, 2020 at 15:56

1 Answer 1

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"; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.